repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
inveniosoftware/invenio-files-rest
invenio_files_rest/storage/pyfs.py
PyFSFileStorage.initialize
def initialize(self, size=0): """Initialize file on storage and truncate to given size.""" fs, path = self._get_fs() # Required for reliably opening the file on certain file systems: if fs.exists(path): fp = fs.open(path, mode='r+b') else: fp = fs.open(path, mode='wb') try: fp.truncate(size) except Exception: fp.close() self.delete() raise finally: fp.close() self._size = size return self.fileurl, size, None
python
def initialize(self, size=0): """Initialize file on storage and truncate to given size.""" fs, path = self._get_fs() # Required for reliably opening the file on certain file systems: if fs.exists(path): fp = fs.open(path, mode='r+b') else: fp = fs.open(path, mode='wb') try: fp.truncate(size) except Exception: fp.close() self.delete() raise finally: fp.close() self._size = size return self.fileurl, size, None
[ "def", "initialize", "(", "self", ",", "size", "=", "0", ")", ":", "fs", ",", "path", "=", "self", ".", "_get_fs", "(", ")", "# Required for reliably opening the file on certain file systems:", "if", "fs", ".", "exists", "(", "path", ")", ":", "fp", "=", "...
Initialize file on storage and truncate to given size.
[ "Initialize", "file", "on", "storage", "and", "truncate", "to", "given", "size", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/pyfs.py#L73-L94
train
41,900
inveniosoftware/invenio-files-rest
invenio_files_rest/storage/pyfs.py
PyFSFileStorage.save
def save(self, incoming_stream, size_limit=None, size=None, chunk_size=None, progress_callback=None): """Save file in the file system.""" fp = self.open(mode='wb') try: bytes_written, checksum = self._write_stream( incoming_stream, fp, chunk_size=chunk_size, progress_callback=progress_callback, size_limit=size_limit, size=size) except Exception: fp.close() self.delete() raise finally: fp.close() self._size = bytes_written return self.fileurl, bytes_written, checksum
python
def save(self, incoming_stream, size_limit=None, size=None, chunk_size=None, progress_callback=None): """Save file in the file system.""" fp = self.open(mode='wb') try: bytes_written, checksum = self._write_stream( incoming_stream, fp, chunk_size=chunk_size, progress_callback=progress_callback, size_limit=size_limit, size=size) except Exception: fp.close() self.delete() raise finally: fp.close() self._size = bytes_written return self.fileurl, bytes_written, checksum
[ "def", "save", "(", "self", ",", "incoming_stream", ",", "size_limit", "=", "None", ",", "size", "=", "None", ",", "chunk_size", "=", "None", ",", "progress_callback", "=", "None", ")", ":", "fp", "=", "self", ".", "open", "(", "mode", "=", "'wb'", "...
Save file in the file system.
[ "Save", "file", "in", "the", "file", "system", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/pyfs.py#L96-L114
train
41,901
inveniosoftware/invenio-files-rest
invenio_files_rest/storage/pyfs.py
PyFSFileStorage.update
def update(self, incoming_stream, seek=0, size=None, chunk_size=None, progress_callback=None): """Update a file in the file system.""" fp = self.open(mode='r+b') try: fp.seek(seek) bytes_written, checksum = self._write_stream( incoming_stream, fp, chunk_size=chunk_size, size=size, progress_callback=progress_callback) finally: fp.close() return bytes_written, checksum
python
def update(self, incoming_stream, seek=0, size=None, chunk_size=None, progress_callback=None): """Update a file in the file system.""" fp = self.open(mode='r+b') try: fp.seek(seek) bytes_written, checksum = self._write_stream( incoming_stream, fp, chunk_size=chunk_size, size=size, progress_callback=progress_callback) finally: fp.close() return bytes_written, checksum
[ "def", "update", "(", "self", ",", "incoming_stream", ",", "seek", "=", "0", ",", "size", "=", "None", ",", "chunk_size", "=", "None", ",", "progress_callback", "=", "None", ")", ":", "fp", "=", "self", ".", "open", "(", "mode", "=", "'r+b'", ")", ...
Update a file in the file system.
[ "Update", "a", "file", "in", "the", "file", "system", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/pyfs.py#L116-L128
train
41,902
inveniosoftware/invenio-files-rest
invenio_files_rest/permissions.py
permission_factory
def permission_factory(obj, action): """Get default permission factory. :param obj: An instance of :class:`invenio_files_rest.models.Bucket` or :class:`invenio_files_rest.models.ObjectVersion` or :class:`invenio_files_rest.models.MultipartObject` or ``None`` if the action is global. :param action: The required action. :raises RuntimeError: If the object is unknown. :returns: A :class:`invenio_access.permissions.Permission` instance. """ need_class = _action2need_map[action] if obj is None: return Permission(need_class(None)) arg = None if isinstance(obj, Bucket): arg = str(obj.id) elif isinstance(obj, ObjectVersion): arg = str(obj.bucket_id) elif isinstance(obj, MultipartObject): arg = str(obj.bucket_id) else: raise RuntimeError('Unknown object') return Permission(need_class(arg))
python
def permission_factory(obj, action): """Get default permission factory. :param obj: An instance of :class:`invenio_files_rest.models.Bucket` or :class:`invenio_files_rest.models.ObjectVersion` or :class:`invenio_files_rest.models.MultipartObject` or ``None`` if the action is global. :param action: The required action. :raises RuntimeError: If the object is unknown. :returns: A :class:`invenio_access.permissions.Permission` instance. """ need_class = _action2need_map[action] if obj is None: return Permission(need_class(None)) arg = None if isinstance(obj, Bucket): arg = str(obj.id) elif isinstance(obj, ObjectVersion): arg = str(obj.bucket_id) elif isinstance(obj, MultipartObject): arg = str(obj.bucket_id) else: raise RuntimeError('Unknown object') return Permission(need_class(arg))
[ "def", "permission_factory", "(", "obj", ",", "action", ")", ":", "need_class", "=", "_action2need_map", "[", "action", "]", "if", "obj", "is", "None", ":", "return", "Permission", "(", "need_class", "(", "None", ")", ")", "arg", "=", "None", "if", "isin...
Get default permission factory. :param obj: An instance of :class:`invenio_files_rest.models.Bucket` or :class:`invenio_files_rest.models.ObjectVersion` or :class:`invenio_files_rest.models.MultipartObject` or ``None`` if the action is global. :param action: The required action. :raises RuntimeError: If the object is unknown. :returns: A :class:`invenio_access.permissions.Permission` instance.
[ "Get", "default", "permission", "factory", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/permissions.py#L112-L138
train
41,903
django-cumulus/django-cumulus
cumulus/management/commands/collectstatic.py
Command.delete_file
def delete_file(self, path, prefixed_path, source_storage): """ Checks if the target file should be deleted if it already exists """ if isinstance(self.storage, CumulusStorage): if self.storage.exists(prefixed_path): try: etag = self.storage._get_object(prefixed_path).etag digest = "{0}".format(hashlib.md5(source_storage.open(path).read()).hexdigest()) if etag == digest: self.log(u"Skipping '{0}' (not modified based on file hash)".format(path)) return False except: raise return super(Command, self).delete_file(path, prefixed_path, source_storage)
python
def delete_file(self, path, prefixed_path, source_storage): """ Checks if the target file should be deleted if it already exists """ if isinstance(self.storage, CumulusStorage): if self.storage.exists(prefixed_path): try: etag = self.storage._get_object(prefixed_path).etag digest = "{0}".format(hashlib.md5(source_storage.open(path).read()).hexdigest()) if etag == digest: self.log(u"Skipping '{0}' (not modified based on file hash)".format(path)) return False except: raise return super(Command, self).delete_file(path, prefixed_path, source_storage)
[ "def", "delete_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "if", "isinstance", "(", "self", ".", "storage", ",", "CumulusStorage", ")", ":", "if", "self", ".", "storage", ".", "exists", "(", "prefixed_path", ")",...
Checks if the target file should be deleted if it already exists
[ "Checks", "if", "the", "target", "file", "should", "be", "deleted", "if", "it", "already", "exists" ]
64feb07b857af28f226be4899e875c29405e261d
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/collectstatic.py#L10-L24
train
41,904
inveniosoftware/invenio-files-rest
examples/app.py
files
def files(): """Load files.""" srcroot = dirname(dirname(__file__)) d = current_app.config['DATADIR'] if exists(d): shutil.rmtree(d) makedirs(d) # Clear data Part.query.delete() MultipartObject.query.delete() ObjectVersion.query.delete() Bucket.query.delete() FileInstance.query.delete() Location.query.delete() db.session.commit() # Create location loc = Location(name='local', uri=d, default=True) db.session.add(loc) db.session.commit() # Bucket 0 b1 = Bucket.create(loc) b1.id = '00000000-0000-0000-0000-000000000000' for f in ['README.rst', 'LICENSE']: with open(join(srcroot, f), 'rb') as fp: ObjectVersion.create(b1, f, stream=fp) # Bucket 1 b2 = Bucket.create(loc) b2.id = '11111111-1111-1111-1111-111111111111' k = 'AUTHORS.rst' with open(join(srcroot, 'CHANGES.rst'), 'rb') as fp: ObjectVersion.create(b2, k, stream=fp) with open(join(srcroot, 'AUTHORS.rst'), 'rb') as fp: ObjectVersion.create(b2, k, stream=fp) k = 'RELEASE-NOTES.rst' with open(join(srcroot, 'RELEASE-NOTES.rst'), 'rb') as fp: ObjectVersion.create(b2, k, stream=fp) with open(join(srcroot, 'CHANGES.rst'), 'rb') as fp: ObjectVersion.create(b2, k, stream=fp) ObjectVersion.delete(b2.id, k) # Bucket 2 b2 = Bucket.create(loc) b2.id = '22222222-2222-2222-2222-222222222222' db.session.commit()
python
def files(): """Load files.""" srcroot = dirname(dirname(__file__)) d = current_app.config['DATADIR'] if exists(d): shutil.rmtree(d) makedirs(d) # Clear data Part.query.delete() MultipartObject.query.delete() ObjectVersion.query.delete() Bucket.query.delete() FileInstance.query.delete() Location.query.delete() db.session.commit() # Create location loc = Location(name='local', uri=d, default=True) db.session.add(loc) db.session.commit() # Bucket 0 b1 = Bucket.create(loc) b1.id = '00000000-0000-0000-0000-000000000000' for f in ['README.rst', 'LICENSE']: with open(join(srcroot, f), 'rb') as fp: ObjectVersion.create(b1, f, stream=fp) # Bucket 1 b2 = Bucket.create(loc) b2.id = '11111111-1111-1111-1111-111111111111' k = 'AUTHORS.rst' with open(join(srcroot, 'CHANGES.rst'), 'rb') as fp: ObjectVersion.create(b2, k, stream=fp) with open(join(srcroot, 'AUTHORS.rst'), 'rb') as fp: ObjectVersion.create(b2, k, stream=fp) k = 'RELEASE-NOTES.rst' with open(join(srcroot, 'RELEASE-NOTES.rst'), 'rb') as fp: ObjectVersion.create(b2, k, stream=fp) with open(join(srcroot, 'CHANGES.rst'), 'rb') as fp: ObjectVersion.create(b2, k, stream=fp) ObjectVersion.delete(b2.id, k) # Bucket 2 b2 = Bucket.create(loc) b2.id = '22222222-2222-2222-2222-222222222222' db.session.commit()
[ "def", "files", "(", ")", ":", "srcroot", "=", "dirname", "(", "dirname", "(", "__file__", ")", ")", "d", "=", "current_app", ".", "config", "[", "'DATADIR'", "]", "if", "exists", "(", "d", ")", ":", "shutil", ".", "rmtree", "(", "d", ")", "makedir...
Load files.
[ "Load", "files", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/examples/app.py#L238-L287
train
41,905
inveniosoftware/invenio-files-rest
invenio_files_rest/cli.py
touch
def touch(): """Create new bucket.""" from .models import Bucket bucket = Bucket.create() db.session.commit() click.secho(str(bucket), fg='green')
python
def touch(): """Create new bucket.""" from .models import Bucket bucket = Bucket.create() db.session.commit() click.secho(str(bucket), fg='green')
[ "def", "touch", "(", ")", ":", "from", ".", "models", "import", "Bucket", "bucket", "=", "Bucket", ".", "create", "(", ")", "db", ".", "session", ".", "commit", "(", ")", "click", ".", "secho", "(", "str", "(", "bucket", ")", ",", "fg", "=", "'gr...
Create new bucket.
[ "Create", "new", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/cli.py#L34-L39
train
41,906
inveniosoftware/invenio-files-rest
invenio_files_rest/cli.py
cp
def cp(source, bucket, checksum, key_prefix): """Create new bucket from all files in directory.""" from .models import Bucket from .helpers import populate_from_path for object_version in populate_from_path( Bucket.get(bucket), source, checksum=checksum, key_prefix=key_prefix): click.secho(str(object_version)) db.session.commit()
python
def cp(source, bucket, checksum, key_prefix): """Create new bucket from all files in directory.""" from .models import Bucket from .helpers import populate_from_path for object_version in populate_from_path( Bucket.get(bucket), source, checksum=checksum, key_prefix=key_prefix): click.secho(str(object_version)) db.session.commit()
[ "def", "cp", "(", "source", ",", "bucket", ",", "checksum", ",", "key_prefix", ")", ":", "from", ".", "models", "import", "Bucket", "from", ".", "helpers", "import", "populate_from_path", "for", "object_version", "in", "populate_from_path", "(", "Bucket", ".",...
Create new bucket from all files in directory.
[ "Create", "new", "bucket", "from", "all", "files", "in", "directory", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/cli.py#L48-L56
train
41,907
inveniosoftware/invenio-files-rest
invenio_files_rest/cli.py
location
def location(name, uri, default): """Create new location.""" from .models import Location location = Location(name=name, uri=uri, default=default) db.session.add(location) db.session.commit() click.secho(str(location), fg='green')
python
def location(name, uri, default): """Create new location.""" from .models import Location location = Location(name=name, uri=uri, default=default) db.session.add(location) db.session.commit() click.secho(str(location), fg='green')
[ "def", "location", "(", "name", ",", "uri", ",", "default", ")", ":", "from", ".", "models", "import", "Location", "location", "=", "Location", "(", "name", "=", "name", ",", "uri", "=", "uri", ",", "default", "=", "default", ")", "db", ".", "session...
Create new location.
[ "Create", "new", "location", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/cli.py#L64-L70
train
41,908
django-cumulus/django-cumulus
cumulus/storage.py
get_content_type
def get_content_type(name, content): """ Checks if the content_type is already set. Otherwise uses the mimetypes library to guess. """ if hasattr(content, "content_type"): content_type = content.content_type else: mime_type, encoding = mimetypes.guess_type(name) content_type = mime_type return content_type
python
def get_content_type(name, content): """ Checks if the content_type is already set. Otherwise uses the mimetypes library to guess. """ if hasattr(content, "content_type"): content_type = content.content_type else: mime_type, encoding = mimetypes.guess_type(name) content_type = mime_type return content_type
[ "def", "get_content_type", "(", "name", ",", "content", ")", ":", "if", "hasattr", "(", "content", ",", "\"content_type\"", ")", ":", "content_type", "=", "content", ".", "content_type", "else", ":", "mime_type", ",", "encoding", "=", "mimetypes", ".", "gues...
Checks if the content_type is already set. Otherwise uses the mimetypes library to guess.
[ "Checks", "if", "the", "content_type", "is", "already", "set", ".", "Otherwise", "uses", "the", "mimetypes", "library", "to", "guess", "." ]
64feb07b857af28f226be4899e875c29405e261d
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/storage.py#L42-L52
train
41,909
django-cumulus/django-cumulus
cumulus/storage.py
sync_headers
def sync_headers(cloud_obj, headers=None, header_patterns=HEADER_PATTERNS): """ Overwrites the given cloud_obj's headers with the ones given as ``headers` and adds additional headers as defined in the HEADERS setting depending on the cloud_obj's file name. """ if headers is None: headers = {} # don't set headers on directories content_type = getattr(cloud_obj, "content_type", None) if content_type == "application/directory": return matched_headers = {} for pattern, pattern_headers in header_patterns: if pattern.match(cloud_obj.name): matched_headers.update(pattern_headers.copy()) # preserve headers already set matched_headers.update(cloud_obj.headers) # explicitly set headers overwrite matches and already set headers matched_headers.update(headers) if matched_headers != cloud_obj.headers: cloud_obj.headers = matched_headers cloud_obj.sync_metadata()
python
def sync_headers(cloud_obj, headers=None, header_patterns=HEADER_PATTERNS): """ Overwrites the given cloud_obj's headers with the ones given as ``headers` and adds additional headers as defined in the HEADERS setting depending on the cloud_obj's file name. """ if headers is None: headers = {} # don't set headers on directories content_type = getattr(cloud_obj, "content_type", None) if content_type == "application/directory": return matched_headers = {} for pattern, pattern_headers in header_patterns: if pattern.match(cloud_obj.name): matched_headers.update(pattern_headers.copy()) # preserve headers already set matched_headers.update(cloud_obj.headers) # explicitly set headers overwrite matches and already set headers matched_headers.update(headers) if matched_headers != cloud_obj.headers: cloud_obj.headers = matched_headers cloud_obj.sync_metadata()
[ "def", "sync_headers", "(", "cloud_obj", ",", "headers", "=", "None", ",", "header_patterns", "=", "HEADER_PATTERNS", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "# don't set headers on directories", "content_type", "=", "getattr", "(...
Overwrites the given cloud_obj's headers with the ones given as ``headers` and adds additional headers as defined in the HEADERS setting depending on the cloud_obj's file name.
[ "Overwrites", "the", "given", "cloud_obj", "s", "headers", "with", "the", "ones", "given", "as", "headers", "and", "adds", "additional", "headers", "as", "defined", "in", "the", "HEADERS", "setting", "depending", "on", "the", "cloud_obj", "s", "file", "name", ...
64feb07b857af28f226be4899e875c29405e261d
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/storage.py#L67-L90
train
41,910
django-cumulus/django-cumulus
cumulus/storage.py
get_gzipped_contents
def get_gzipped_contents(input_file): """ Returns a gzipped version of a previously opened file's buffer. """ zbuf = StringIO() zfile = GzipFile(mode="wb", compresslevel=6, fileobj=zbuf) zfile.write(input_file.read()) zfile.close() return ContentFile(zbuf.getvalue())
python
def get_gzipped_contents(input_file): """ Returns a gzipped version of a previously opened file's buffer. """ zbuf = StringIO() zfile = GzipFile(mode="wb", compresslevel=6, fileobj=zbuf) zfile.write(input_file.read()) zfile.close() return ContentFile(zbuf.getvalue())
[ "def", "get_gzipped_contents", "(", "input_file", ")", ":", "zbuf", "=", "StringIO", "(", ")", "zfile", "=", "GzipFile", "(", "mode", "=", "\"wb\"", ",", "compresslevel", "=", "6", ",", "fileobj", "=", "zbuf", ")", "zfile", ".", "write", "(", "input_file...
Returns a gzipped version of a previously opened file's buffer.
[ "Returns", "a", "gzipped", "version", "of", "a", "previously", "opened", "file", "s", "buffer", "." ]
64feb07b857af28f226be4899e875c29405e261d
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/storage.py#L93-L101
train
41,911
inveniosoftware/invenio-files-rest
invenio_files_rest/serializer.py
schema_from_context
def schema_from_context(context): """Determine which schema to use.""" item_class = context.get('class') return ( serializer_mapping[item_class] if item_class else BaseSchema, context.get('many', False) )
python
def schema_from_context(context): """Determine which schema to use.""" item_class = context.get('class') return ( serializer_mapping[item_class] if item_class else BaseSchema, context.get('many', False) )
[ "def", "schema_from_context", "(", "context", ")", ":", "item_class", "=", "context", ".", "get", "(", "'class'", ")", "return", "(", "serializer_mapping", "[", "item_class", "]", "if", "item_class", "else", "BaseSchema", ",", "context", ".", "get", "(", "'m...
Determine which schema to use.
[ "Determine", "which", "schema", "to", "use", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/serializer.py#L201-L207
train
41,912
inveniosoftware/invenio-files-rest
invenio_files_rest/serializer.py
wait_for_taskresult
def wait_for_taskresult(task_result, content, interval, max_rounds): """Get helper to wait for async task result to finish. The task will periodically send whitespace to prevent the connection from being closed. :param task_result: The async task to wait for. :param content: The content to return when the task is ready. :param interval: The duration of a sleep period before check again if the task is ready. :param max_rounds: The maximum number of intervals the function check before returning an Exception. :returns: An iterator on the content or a :class:`invenio_files_rest.errors.FilesException` exception if the timeout happened or the job failed. """ assert max_rounds > 0 def _whitespace_waiting(): current = 0 while current < max_rounds and current != -1: if task_result.ready(): # Task is done and we return current = -1 if task_result.successful(): yield content else: yield FilesException( description='Job failed.' ).get_body() else: # Send whitespace to prevent connection from closing. current += 1 sleep(interval) yield b' ' # Timed-out reached if current == max_rounds: yield FilesException( description='Job timed out.' ).get_body() return _whitespace_waiting()
python
def wait_for_taskresult(task_result, content, interval, max_rounds): """Get helper to wait for async task result to finish. The task will periodically send whitespace to prevent the connection from being closed. :param task_result: The async task to wait for. :param content: The content to return when the task is ready. :param interval: The duration of a sleep period before check again if the task is ready. :param max_rounds: The maximum number of intervals the function check before returning an Exception. :returns: An iterator on the content or a :class:`invenio_files_rest.errors.FilesException` exception if the timeout happened or the job failed. """ assert max_rounds > 0 def _whitespace_waiting(): current = 0 while current < max_rounds and current != -1: if task_result.ready(): # Task is done and we return current = -1 if task_result.successful(): yield content else: yield FilesException( description='Job failed.' ).get_body() else: # Send whitespace to prevent connection from closing. current += 1 sleep(interval) yield b' ' # Timed-out reached if current == max_rounds: yield FilesException( description='Job timed out.' ).get_body() return _whitespace_waiting()
[ "def", "wait_for_taskresult", "(", "task_result", ",", "content", ",", "interval", ",", "max_rounds", ")", ":", "assert", "max_rounds", ">", "0", "def", "_whitespace_waiting", "(", ")", ":", "current", "=", "0", "while", "current", "<", "max_rounds", "and", ...
Get helper to wait for async task result to finish. The task will periodically send whitespace to prevent the connection from being closed. :param task_result: The async task to wait for. :param content: The content to return when the task is ready. :param interval: The duration of a sleep period before check again if the task is ready. :param max_rounds: The maximum number of intervals the function check before returning an Exception. :returns: An iterator on the content or a :class:`invenio_files_rest.errors.FilesException` exception if the timeout happened or the job failed.
[ "Get", "helper", "to", "wait", "for", "async", "task", "result", "to", "finish", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/serializer.py#L223-L265
train
41,913
inveniosoftware/invenio-files-rest
invenio_files_rest/serializer.py
json_serializer
def json_serializer(data=None, code=200, headers=None, context=None, etag=None, task_result=None): """Build a json flask response using the given data. :param data: The data to serialize. (Default: ``None``) :param code: The HTTP status code. (Default: ``200``) :param headers: The HTTP headers to include. (Default: ``None``) :param context: The schema class context. (Default: ``None``) :param etag: The ETag header. (Default: ``None``) :param task_result: Optionally you can pass async task to wait for. (Default: ``None``) :returns: A Flask response with json data. :rtype: :py:class:`flask.Response` """ schema_class, many = schema_from_context(context or {}) if data is not None: # Generate JSON response data = json.dumps( schema_class(context=context).dump(data, many=many).data, **_format_args() ) interval = current_app.config['FILES_REST_TASK_WAIT_INTERVAL'] max_rounds = int( current_app.config['FILES_REST_TASK_WAIT_MAX_SECONDS'] // interval ) response = current_app.response_class( # Stream response if waiting for task result. data if task_result is None else wait_for_taskresult( task_result, data, interval, max_rounds, ), mimetype='application/json' ) else: response = current_app.response_class(mimetype='application/json') response.status_code = code if headers is not None: response.headers.extend(headers) if etag: response.set_etag(etag) return response
python
def json_serializer(data=None, code=200, headers=None, context=None, etag=None, task_result=None): """Build a json flask response using the given data. :param data: The data to serialize. (Default: ``None``) :param code: The HTTP status code. (Default: ``200``) :param headers: The HTTP headers to include. (Default: ``None``) :param context: The schema class context. (Default: ``None``) :param etag: The ETag header. (Default: ``None``) :param task_result: Optionally you can pass async task to wait for. (Default: ``None``) :returns: A Flask response with json data. :rtype: :py:class:`flask.Response` """ schema_class, many = schema_from_context(context or {}) if data is not None: # Generate JSON response data = json.dumps( schema_class(context=context).dump(data, many=many).data, **_format_args() ) interval = current_app.config['FILES_REST_TASK_WAIT_INTERVAL'] max_rounds = int( current_app.config['FILES_REST_TASK_WAIT_MAX_SECONDS'] // interval ) response = current_app.response_class( # Stream response if waiting for task result. data if task_result is None else wait_for_taskresult( task_result, data, interval, max_rounds, ), mimetype='application/json' ) else: response = current_app.response_class(mimetype='application/json') response.status_code = code if headers is not None: response.headers.extend(headers) if etag: response.set_etag(etag) return response
[ "def", "json_serializer", "(", "data", "=", "None", ",", "code", "=", "200", ",", "headers", "=", "None", ",", "context", "=", "None", ",", "etag", "=", "None", ",", "task_result", "=", "None", ")", ":", "schema_class", ",", "many", "=", "schema_from_c...
Build a json flask response using the given data. :param data: The data to serialize. (Default: ``None``) :param code: The HTTP status code. (Default: ``200``) :param headers: The HTTP headers to include. (Default: ``None``) :param context: The schema class context. (Default: ``None``) :param etag: The ETag header. (Default: ``None``) :param task_result: Optionally you can pass async task to wait for. (Default: ``None``) :returns: A Flask response with json data. :rtype: :py:class:`flask.Response`
[ "Build", "a", "json", "flask", "response", "using", "the", "given", "data", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/serializer.py#L268-L312
train
41,914
swistakm/python-gmaps
src/gmaps/directions.py
Directions.directions
def directions(self, origin, destination, mode=None, alternatives=None, waypoints=None, optimize_waypoints=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, sensor=None): """Get directions between locations :param origin: Origin location - string address; (latitude, longitude) two-tuple, dict with ("lat", "lon") keys or object with (lat, lon) attributes :param destination: Destination location - type same as origin :param mode: Travel mode as string, defaults to "driving". See `google docs details <https://developers.google.com/maps/documentation/directions/#TravelModes>`_ :param alternatives: True if provide it has to return more then one route alternative :param waypoints: Iterable with set of intermediate stops, like ("Munich", "Dallas") See `google docs details <https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest>`_ :param optimize_waypoints: if true will attempt to re-order supplied waypoints to minimize overall cost of the route. If waypoints are optimized, the route returned will show the optimized order under "waypoint_order". See `google docs details <https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest>`_ :param avoid: Iterable with set of restrictions, like ("tolls", "highways"). For full list refer to `google docs details <https://developers.google.com/maps/documentation/directions/#Restrictions>`_ :param language: The language in which to return results. See `list of supported languages <https://developers.google.com/maps/faq#languagesupport>`_ :param units: Unit system for result. Defaults to unit system of origin's country. See `google docs details <https://developers.google.com/maps/documentation/directions/#UnitSystems>`_ :param region: The region code. Affects geocoding of origin and destination (see `gmaps.Geocoding.geocode` region parameter) :param departure_time: Desired time of departure as seconds since midnight, January 1, 1970 UTC :param arrival_time: Desired time of arrival for transit directions as seconds since midnight, January 1, 1970 UTC. """ # noqa if optimize_waypoints: waypoints.insert(0, "optimize:true") parameters = dict( origin=self.assume_latlon_or_address(origin), destination=self.assume_latlon_or_address(destination), mode=mode, alternatives=alternatives, waypoints=waypoints or [], avoid=avoid, language=language, units=units, region=region, departure_time=departure_time, arrival_time=arrival_time, sensor=sensor, ) return self._make_request(self.DIRECTIONS_URL, parameters, "routes")
python
def directions(self, origin, destination, mode=None, alternatives=None, waypoints=None, optimize_waypoints=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, sensor=None): """Get directions between locations :param origin: Origin location - string address; (latitude, longitude) two-tuple, dict with ("lat", "lon") keys or object with (lat, lon) attributes :param destination: Destination location - type same as origin :param mode: Travel mode as string, defaults to "driving". See `google docs details <https://developers.google.com/maps/documentation/directions/#TravelModes>`_ :param alternatives: True if provide it has to return more then one route alternative :param waypoints: Iterable with set of intermediate stops, like ("Munich", "Dallas") See `google docs details <https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest>`_ :param optimize_waypoints: if true will attempt to re-order supplied waypoints to minimize overall cost of the route. If waypoints are optimized, the route returned will show the optimized order under "waypoint_order". See `google docs details <https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest>`_ :param avoid: Iterable with set of restrictions, like ("tolls", "highways"). For full list refer to `google docs details <https://developers.google.com/maps/documentation/directions/#Restrictions>`_ :param language: The language in which to return results. See `list of supported languages <https://developers.google.com/maps/faq#languagesupport>`_ :param units: Unit system for result. Defaults to unit system of origin's country. See `google docs details <https://developers.google.com/maps/documentation/directions/#UnitSystems>`_ :param region: The region code. Affects geocoding of origin and destination (see `gmaps.Geocoding.geocode` region parameter) :param departure_time: Desired time of departure as seconds since midnight, January 1, 1970 UTC :param arrival_time: Desired time of arrival for transit directions as seconds since midnight, January 1, 1970 UTC. """ # noqa if optimize_waypoints: waypoints.insert(0, "optimize:true") parameters = dict( origin=self.assume_latlon_or_address(origin), destination=self.assume_latlon_or_address(destination), mode=mode, alternatives=alternatives, waypoints=waypoints or [], avoid=avoid, language=language, units=units, region=region, departure_time=departure_time, arrival_time=arrival_time, sensor=sensor, ) return self._make_request(self.DIRECTIONS_URL, parameters, "routes")
[ "def", "directions", "(", "self", ",", "origin", ",", "destination", ",", "mode", "=", "None", ",", "alternatives", "=", "None", ",", "waypoints", "=", "None", ",", "optimize_waypoints", "=", "False", ",", "avoid", "=", "None", ",", "language", "=", "Non...
Get directions between locations :param origin: Origin location - string address; (latitude, longitude) two-tuple, dict with ("lat", "lon") keys or object with (lat, lon) attributes :param destination: Destination location - type same as origin :param mode: Travel mode as string, defaults to "driving". See `google docs details <https://developers.google.com/maps/documentation/directions/#TravelModes>`_ :param alternatives: True if provide it has to return more then one route alternative :param waypoints: Iterable with set of intermediate stops, like ("Munich", "Dallas") See `google docs details <https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest>`_ :param optimize_waypoints: if true will attempt to re-order supplied waypoints to minimize overall cost of the route. If waypoints are optimized, the route returned will show the optimized order under "waypoint_order". See `google docs details <https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest>`_ :param avoid: Iterable with set of restrictions, like ("tolls", "highways"). For full list refer to `google docs details <https://developers.google.com/maps/documentation/directions/#Restrictions>`_ :param language: The language in which to return results. See `list of supported languages <https://developers.google.com/maps/faq#languagesupport>`_ :param units: Unit system for result. Defaults to unit system of origin's country. See `google docs details <https://developers.google.com/maps/documentation/directions/#UnitSystems>`_ :param region: The region code. Affects geocoding of origin and destination (see `gmaps.Geocoding.geocode` region parameter) :param departure_time: Desired time of departure as seconds since midnight, January 1, 1970 UTC :param arrival_time: Desired time of arrival for transit directions as seconds since midnight, January 1, 1970 UTC.
[ "Get", "directions", "between", "locations" ]
ef3bdea6f02277200f21a09f99d4e2aebad762b9
https://github.com/swistakm/python-gmaps/blob/ef3bdea6f02277200f21a09f99d4e2aebad762b9/src/gmaps/directions.py#L8-L61
train
41,915
inveniosoftware/invenio-files-rest
invenio_files_rest/utils.py
guess_mimetype
def guess_mimetype(filename): """Map extra mimetype with the encoding provided. :returns: The extra mimetype. """ m, encoding = mimetypes.guess_type(filename) if encoding: m = ENCODING_MIMETYPES.get(encoding, None) return m or 'application/octet-stream'
python
def guess_mimetype(filename): """Map extra mimetype with the encoding provided. :returns: The extra mimetype. """ m, encoding = mimetypes.guess_type(filename) if encoding: m = ENCODING_MIMETYPES.get(encoding, None) return m or 'application/octet-stream'
[ "def", "guess_mimetype", "(", "filename", ")", ":", "m", ",", "encoding", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "if", "encoding", ":", "m", "=", "ENCODING_MIMETYPES", ".", "get", "(", "encoding", ",", "None", ")", "return", "m", "or"...
Map extra mimetype with the encoding provided. :returns: The extra mimetype.
[ "Map", "extra", "mimetype", "with", "the", "encoding", "provided", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/utils.py#L50-L58
train
41,916
inveniosoftware/invenio-files-rest
invenio_files_rest/admin.py
link
def link(text, link_func): """Generate a object formatter for links..""" def object_formatter(v, c, m, p): """Format object view link.""" return Markup('<a href="{0}">{1}</a>'.format( link_func(m), text)) return object_formatter
python
def link(text, link_func): """Generate a object formatter for links..""" def object_formatter(v, c, m, p): """Format object view link.""" return Markup('<a href="{0}">{1}</a>'.format( link_func(m), text)) return object_formatter
[ "def", "link", "(", "text", ",", "link_func", ")", ":", "def", "object_formatter", "(", "v", ",", "c", ",", "m", ",", "p", ")", ":", "\"\"\"Format object view link.\"\"\"", "return", "Markup", "(", "'<a href=\"{0}\">{1}</a>'", ".", "format", "(", "link_func", ...
Generate a object formatter for links..
[ "Generate", "a", "object", "formatter", "for", "links", ".." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/admin.py#L40-L46
train
41,917
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
validate_tag
def validate_tag(key, value): """Validate a tag. Keys must be less than 128 chars and values must be less than 256 chars. """ # Note, parse_sql does not include a keys if the value is an empty string # (e.g. 'key=&test=a'), and thus technically we should not get strings # which have zero length. klen = len(key) vlen = len(value) return klen > 0 and klen < 256 and vlen > 0 and vlen < 256
python
def validate_tag(key, value): """Validate a tag. Keys must be less than 128 chars and values must be less than 256 chars. """ # Note, parse_sql does not include a keys if the value is an empty string # (e.g. 'key=&test=a'), and thus technically we should not get strings # which have zero length. klen = len(key) vlen = len(value) return klen > 0 and klen < 256 and vlen > 0 and vlen < 256
[ "def", "validate_tag", "(", "key", ",", "value", ")", ":", "# Note, parse_sql does not include a keys if the value is an empty string", "# (e.g. 'key=&test=a'), and thus technically we should not get strings", "# which have zero length.", "klen", "=", "len", "(", "key", ")", "vlen"...
Validate a tag. Keys must be less than 128 chars and values must be less than 256 chars.
[ "Validate", "a", "tag", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L67-L78
train
41,918
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
parse_header_tags
def parse_header_tags(): """Parse tags specified in the HTTP request header.""" # Get the value of the custom HTTP header and interpret it as an query # string qs = request.headers.get( current_app.config['FILES_REST_FILE_TAGS_HEADER'], '') tags = {} for key, value in parse_qsl(qs): # Check for duplicate keys if key in tags: raise DuplicateTagError() # Check for too short/long keys and values. if not validate_tag(key, value): raise InvalidTagError() tags[key] = value return tags or None
python
def parse_header_tags(): """Parse tags specified in the HTTP request header.""" # Get the value of the custom HTTP header and interpret it as an query # string qs = request.headers.get( current_app.config['FILES_REST_FILE_TAGS_HEADER'], '') tags = {} for key, value in parse_qsl(qs): # Check for duplicate keys if key in tags: raise DuplicateTagError() # Check for too short/long keys and values. if not validate_tag(key, value): raise InvalidTagError() tags[key] = value return tags or None
[ "def", "parse_header_tags", "(", ")", ":", "# Get the value of the custom HTTP header and interpret it as an query", "# string", "qs", "=", "request", ".", "headers", ".", "get", "(", "current_app", ".", "config", "[", "'FILES_REST_FILE_TAGS_HEADER'", "]", ",", "''", ")...
Parse tags specified in the HTTP request header.
[ "Parse", "tags", "specified", "in", "the", "HTTP", "request", "header", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L81-L97
train
41,919
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
default_partfactory
def default_partfactory(part_number=None, content_length=None, content_type=None, content_md5=None): """Get default part factory. :param part_number: The part number. (Default: ``None``) :param content_length: The content length. (Default: ``None``) :param content_type: The HTTP Content-Type. (Default: ``None``) :param content_md5: The content MD5. (Default: ``None``) :returns: The content length, the part number, the stream, the content type, MD5 of the content. """ return content_length, part_number, request.stream, content_type, \ content_md5, None
python
def default_partfactory(part_number=None, content_length=None, content_type=None, content_md5=None): """Get default part factory. :param part_number: The part number. (Default: ``None``) :param content_length: The content length. (Default: ``None``) :param content_type: The HTTP Content-Type. (Default: ``None``) :param content_md5: The content MD5. (Default: ``None``) :returns: The content length, the part number, the stream, the content type, MD5 of the content. """ return content_length, part_number, request.stream, content_type, \ content_md5, None
[ "def", "default_partfactory", "(", "part_number", "=", "None", ",", "content_length", "=", "None", ",", "content_type", "=", "None", ",", "content_md5", "=", "None", ")", ":", "return", "content_length", ",", "part_number", ",", "request", ".", "stream", ",", ...
Get default part factory. :param part_number: The part number. (Default: ``None``) :param content_length: The content length. (Default: ``None``) :param content_type: The HTTP Content-Type. (Default: ``None``) :param content_md5: The content MD5. (Default: ``None``) :returns: The content length, the part number, the stream, the content type, MD5 of the content.
[ "Get", "default", "part", "factory", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L124-L136
train
41,920
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ngfileupload_partfactory
def ngfileupload_partfactory(part_number=None, content_length=None, uploaded_file=None): """Part factory for ng-file-upload. :param part_number: The part number. (Default: ``None``) :param content_length: The content length. (Default: ``None``) :param uploaded_file: The upload request. (Default: ``None``) :returns: The content length, part number, stream, HTTP Content-Type header. """ return content_length, part_number, uploaded_file.stream, \ uploaded_file.headers.get('Content-Type'), None, None
python
def ngfileupload_partfactory(part_number=None, content_length=None, uploaded_file=None): """Part factory for ng-file-upload. :param part_number: The part number. (Default: ``None``) :param content_length: The content length. (Default: ``None``) :param uploaded_file: The upload request. (Default: ``None``) :returns: The content length, part number, stream, HTTP Content-Type header. """ return content_length, part_number, uploaded_file.stream, \ uploaded_file.headers.get('Content-Type'), None, None
[ "def", "ngfileupload_partfactory", "(", "part_number", "=", "None", ",", "content_length", "=", "None", ",", "uploaded_file", "=", "None", ")", ":", "return", "content_length", ",", "part_number", ",", "uploaded_file", ".", "stream", ",", "uploaded_file", ".", "...
Part factory for ng-file-upload. :param part_number: The part number. (Default: ``None``) :param content_length: The content length. (Default: ``None``) :param uploaded_file: The upload request. (Default: ``None``) :returns: The content length, part number, stream, HTTP Content-Type header.
[ "Part", "factory", "for", "ng", "-", "file", "-", "upload", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L192-L203
train
41,921
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
pass_bucket
def pass_bucket(f): """Decorate to retrieve a bucket.""" @wraps(f) def decorate(*args, **kwargs): bucket_id = kwargs.pop('bucket_id') bucket = Bucket.get(as_uuid(bucket_id)) if not bucket: abort(404, 'Bucket does not exist.') return f(bucket=bucket, *args, **kwargs) return decorate
python
def pass_bucket(f): """Decorate to retrieve a bucket.""" @wraps(f) def decorate(*args, **kwargs): bucket_id = kwargs.pop('bucket_id') bucket = Bucket.get(as_uuid(bucket_id)) if not bucket: abort(404, 'Bucket does not exist.') return f(bucket=bucket, *args, **kwargs) return decorate
[ "def", "pass_bucket", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "bucket_id", "=", "kwargs", ".", "pop", "(", "'bucket_id'", ")", "bucket", "=", "Bucket", ".", "get", "...
Decorate to retrieve a bucket.
[ "Decorate", "to", "retrieve", "a", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L244-L253
train
41,922
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
pass_multipart
def pass_multipart(with_completed=False): """Decorate to retrieve an object.""" def decorate(f): @wraps(f) def inner(self, bucket, key, upload_id, *args, **kwargs): obj = MultipartObject.get( bucket, key, upload_id, with_completed=with_completed) if obj is None: abort(404, 'uploadId does not exists.') return f(self, obj, *args, **kwargs) return inner return decorate
python
def pass_multipart(with_completed=False): """Decorate to retrieve an object.""" def decorate(f): @wraps(f) def inner(self, bucket, key, upload_id, *args, **kwargs): obj = MultipartObject.get( bucket, key, upload_id, with_completed=with_completed) if obj is None: abort(404, 'uploadId does not exists.') return f(self, obj, *args, **kwargs) return inner return decorate
[ "def", "pass_multipart", "(", "with_completed", "=", "False", ")", ":", "def", "decorate", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "inner", "(", "self", ",", "bucket", ",", "key", ",", "upload_id", ",", "*", "args", ",", "*", "*", ...
Decorate to retrieve an object.
[ "Decorate", "to", "retrieve", "an", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L256-L267
train
41,923
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
check_permission
def check_permission(permission, hidden=True): """Check if permission is allowed. If permission fails then the connection is aborted. :param permission: The permission to check. :param hidden: Determine if a 404 error (``True``) or 401/403 error (``False``) should be returned if the permission is rejected (i.e. hide or reveal the existence of a particular object). """ if permission is not None and not permission.can(): if hidden: abort(404) else: if current_user.is_authenticated: abort(403, 'You do not have a permission for this action') abort(401)
python
def check_permission(permission, hidden=True): """Check if permission is allowed. If permission fails then the connection is aborted. :param permission: The permission to check. :param hidden: Determine if a 404 error (``True``) or 401/403 error (``False``) should be returned if the permission is rejected (i.e. hide or reveal the existence of a particular object). """ if permission is not None and not permission.can(): if hidden: abort(404) else: if current_user.is_authenticated: abort(403, 'You do not have a permission for this action') abort(401)
[ "def", "check_permission", "(", "permission", ",", "hidden", "=", "True", ")", ":", "if", "permission", "is", "not", "None", "and", "not", "permission", ".", "can", "(", ")", ":", "if", "hidden", ":", "abort", "(", "404", ")", "else", ":", "if", "cur...
Check if permission is allowed. If permission fails then the connection is aborted. :param permission: The permission to check. :param hidden: Determine if a 404 error (``True``) or 401/403 error (``False``) should be returned if the permission is rejected (i.e. hide or reveal the existence of a particular object).
[ "Check", "if", "permission", "is", "allowed", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L273-L290
train
41,924
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
need_permissions
def need_permissions(object_getter, action, hidden=True): """Get permission for buckets or abort. :param object_getter: The function used to retrieve the object and pass it to the permission factory. :param action: The action needed. :param hidden: Determine which kind of error to return. (Default: ``True``) """ def decorator_builder(f): @wraps(f) def decorate(*args, **kwargs): check_permission(current_permission_factory( object_getter(*args, **kwargs), action(*args, **kwargs) if callable(action) else action, ), hidden=hidden) return f(*args, **kwargs) return decorate return decorator_builder
python
def need_permissions(object_getter, action, hidden=True): """Get permission for buckets or abort. :param object_getter: The function used to retrieve the object and pass it to the permission factory. :param action: The action needed. :param hidden: Determine which kind of error to return. (Default: ``True``) """ def decorator_builder(f): @wraps(f) def decorate(*args, **kwargs): check_permission(current_permission_factory( object_getter(*args, **kwargs), action(*args, **kwargs) if callable(action) else action, ), hidden=hidden) return f(*args, **kwargs) return decorate return decorator_builder
[ "def", "need_permissions", "(", "object_getter", ",", "action", ",", "hidden", "=", "True", ")", ":", "def", "decorator_builder", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":",...
Get permission for buckets or abort. :param object_getter: The function used to retrieve the object and pass it to the permission factory. :param action: The action needed. :param hidden: Determine which kind of error to return. (Default: ``True``)
[ "Get", "permission", "for", "buckets", "or", "abort", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L293-L311
train
41,925
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
LocationResource.post
def post(self): """Create bucket.""" with db.session.begin_nested(): bucket = Bucket.create( storage_class=current_app.config[ 'FILES_REST_DEFAULT_STORAGE_CLASS' ], ) db.session.commit() return self.make_response( data=bucket, context={ 'class': Bucket, } )
python
def post(self): """Create bucket.""" with db.session.begin_nested(): bucket = Bucket.create( storage_class=current_app.config[ 'FILES_REST_DEFAULT_STORAGE_CLASS' ], ) db.session.commit() return self.make_response( data=bucket, context={ 'class': Bucket, } )
[ "def", "post", "(", "self", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "bucket", "=", "Bucket", ".", "create", "(", "storage_class", "=", "current_app", ".", "config", "[", "'FILES_REST_DEFAULT_STORAGE_CLASS'", "]", ",", ")...
Create bucket.
[ "Create", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L337-L351
train
41,926
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
BucketResource.get
def get(self, bucket=None, versions=missing, uploads=missing): """Get list of objects in the bucket. :param bucket: A :class:`invenio_files_rest.models.Bucket` instance. :returns: The Flask response. """ if uploads is not missing: return self.multipart_listuploads(bucket) else: return self.listobjects(bucket, versions)
python
def get(self, bucket=None, versions=missing, uploads=missing): """Get list of objects in the bucket. :param bucket: A :class:`invenio_files_rest.models.Bucket` instance. :returns: The Flask response. """ if uploads is not missing: return self.multipart_listuploads(bucket) else: return self.listobjects(bucket, versions)
[ "def", "get", "(", "self", ",", "bucket", "=", "None", ",", "versions", "=", "missing", ",", "uploads", "=", "missing", ")", ":", "if", "uploads", "is", "not", "missing", ":", "return", "self", ".", "multipart_listuploads", "(", "bucket", ")", "else", ...
Get list of objects in the bucket. :param bucket: A :class:`invenio_files_rest.models.Bucket` instance. :returns: The Flask response.
[ "Get", "list", "of", "objects", "in", "the", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L413-L422
train
41,927
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ObjectResource.send_object
def send_object(bucket, obj, expected_chksum=None, logger_data=None, restricted=True, as_attachment=False): """Send an object for a given bucket. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :params expected_chksum: Expected checksum. :param logger_data: The python logger. :param kwargs: Keyword arguments passed to ``Object.send_file()`` :returns: A Flask response. """ if not obj.is_head: check_permission( current_permission_factory(obj, 'object-read-version'), hidden=False ) if expected_chksum and obj.file.checksum != expected_chksum: current_app.logger.warning( 'File checksum mismatch detected.', extra=logger_data) file_downloaded.send(current_app._get_current_object(), obj=obj) return obj.send_file(restricted=restricted, as_attachment=as_attachment)
python
def send_object(bucket, obj, expected_chksum=None, logger_data=None, restricted=True, as_attachment=False): """Send an object for a given bucket. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :params expected_chksum: Expected checksum. :param logger_data: The python logger. :param kwargs: Keyword arguments passed to ``Object.send_file()`` :returns: A Flask response. """ if not obj.is_head: check_permission( current_permission_factory(obj, 'object-read-version'), hidden=False ) if expected_chksum and obj.file.checksum != expected_chksum: current_app.logger.warning( 'File checksum mismatch detected.', extra=logger_data) file_downloaded.send(current_app._get_current_object(), obj=obj) return obj.send_file(restricted=restricted, as_attachment=as_attachment)
[ "def", "send_object", "(", "bucket", ",", "obj", ",", "expected_chksum", "=", "None", ",", "logger_data", "=", "None", ",", "restricted", "=", "True", ",", "as_attachment", "=", "False", ")", ":", "if", "not", "obj", ".", "is_head", ":", "check_permission"...
Send an object for a given bucket. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :params expected_chksum: Expected checksum. :param logger_data: The python logger. :param kwargs: Keyword arguments passed to ``Object.send_file()`` :returns: A Flask response.
[ "Send", "an", "object", "for", "a", "given", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L601-L625
train
41,928
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ObjectResource.multipart_listparts
def multipart_listparts(self, multipart): """Get parts of a multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response. """ return self.make_response( data=Part.query_by_multipart( multipart).order_by(Part.part_number).limit(1000).all(), context={ 'class': Part, 'multipart': multipart, 'many': True, } )
python
def multipart_listparts(self, multipart): """Get parts of a multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response. """ return self.make_response( data=Part.query_by_multipart( multipart).order_by(Part.part_number).limit(1000).all(), context={ 'class': Part, 'multipart': multipart, 'many': True, } )
[ "def", "multipart_listparts", "(", "self", ",", "multipart", ")", ":", "return", "self", ".", "make_response", "(", "data", "=", "Part", ".", "query_by_multipart", "(", "multipart", ")", ".", "order_by", "(", "Part", ".", "part_number", ")", ".", "limit", ...
Get parts of a multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response.
[ "Get", "parts", "of", "a", "multipart", "upload", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L635-L650
train
41,929
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ObjectResource.multipart_init
def multipart_init(self, bucket, key, size=None, part_size=None): """Initialize a multipart upload. :param bucket: The bucket (instance or id) to get the object from. :param key: The file key. :param size: The total size. :param part_size: The part size. :raises invenio_files_rest.errors.MissingQueryParameter: If size or part_size are not defined. :returns: A Flask response. """ if size is None: raise MissingQueryParameter('size') if part_size is None: raise MissingQueryParameter('partSize') multipart = MultipartObject.create(bucket, key, size, part_size) db.session.commit() return self.make_response( data=multipart, context={ 'class': MultipartObject, 'bucket': bucket, } )
python
def multipart_init(self, bucket, key, size=None, part_size=None): """Initialize a multipart upload. :param bucket: The bucket (instance or id) to get the object from. :param key: The file key. :param size: The total size. :param part_size: The part size. :raises invenio_files_rest.errors.MissingQueryParameter: If size or part_size are not defined. :returns: A Flask response. """ if size is None: raise MissingQueryParameter('size') if part_size is None: raise MissingQueryParameter('partSize') multipart = MultipartObject.create(bucket, key, size, part_size) db.session.commit() return self.make_response( data=multipart, context={ 'class': MultipartObject, 'bucket': bucket, } )
[ "def", "multipart_init", "(", "self", ",", "bucket", ",", "key", ",", "size", "=", "None", ",", "part_size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "raise", "MissingQueryParameter", "(", "'size'", ")", "if", "part_size", "is", "None", ...
Initialize a multipart upload. :param bucket: The bucket (instance or id) to get the object from. :param key: The file key. :param size: The total size. :param part_size: The part size. :raises invenio_files_rest.errors.MissingQueryParameter: If size or part_size are not defined. :returns: A Flask response.
[ "Initialize", "a", "multipart", "upload", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L653-L676
train
41,930
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ObjectResource.multipart_uploadpart
def multipart_uploadpart(self, multipart): """Upload a part. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response. """ content_length, part_number, stream, content_type, content_md5, tags =\ current_files_rest.multipart_partfactory() if content_length: ck = multipart.last_part_size if \ part_number == multipart.last_part_number \ else multipart.chunk_size if ck != content_length: raise MultipartInvalidChunkSize() # Create part try: p = Part.get_or_create(multipart, part_number) p.set_contents(stream) db.session.commit() except Exception: # We remove the Part since incomplete data may have been written to # disk (e.g. client closed connection etc.) so it must be # reuploaded. db.session.rollback() Part.delete(multipart, part_number) raise return self.make_response( data=p, context={ 'class': Part, }, etag=p.checksum )
python
def multipart_uploadpart(self, multipart): """Upload a part. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response. """ content_length, part_number, stream, content_type, content_md5, tags =\ current_files_rest.multipart_partfactory() if content_length: ck = multipart.last_part_size if \ part_number == multipart.last_part_number \ else multipart.chunk_size if ck != content_length: raise MultipartInvalidChunkSize() # Create part try: p = Part.get_or_create(multipart, part_number) p.set_contents(stream) db.session.commit() except Exception: # We remove the Part since incomplete data may have been written to # disk (e.g. client closed connection etc.) so it must be # reuploaded. db.session.rollback() Part.delete(multipart, part_number) raise return self.make_response( data=p, context={ 'class': Part, }, etag=p.checksum )
[ "def", "multipart_uploadpart", "(", "self", ",", "multipart", ")", ":", "content_length", ",", "part_number", ",", "stream", ",", "content_type", ",", "content_md5", ",", "tags", "=", "current_files_rest", ".", "multipart_partfactory", "(", ")", "if", "content_len...
Upload a part. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response.
[ "Upload", "a", "part", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L679-L715
train
41,931
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ObjectResource.multipart_delete
def multipart_delete(self, multipart): """Abort a multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response. """ multipart.delete() db.session.commit() if multipart.file_id: remove_file_data.delay(str(multipart.file_id)) return self.make_response('', 204)
python
def multipart_delete(self, multipart): """Abort a multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response. """ multipart.delete() db.session.commit() if multipart.file_id: remove_file_data.delay(str(multipart.file_id)) return self.make_response('', 204)
[ "def", "multipart_delete", "(", "self", ",", "multipart", ")", ":", "multipart", ".", "delete", "(", ")", "db", ".", "session", ".", "commit", "(", ")", "if", "multipart", ".", "file_id", ":", "remove_file_data", ".", "delay", "(", "str", "(", "multipart...
Abort a multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A Flask response.
[ "Abort", "a", "multipart", "upload", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L750-L761
train
41,932
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ObjectResource.get
def get(self, bucket=None, key=None, version_id=None, upload_id=None, uploads=None, download=None): """Get object or list parts of a multpart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param version_id: The version ID. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :param download: The download flag. (Default: ``None``) :returns: A Flask response. """ if upload_id: return self.multipart_listparts(bucket, key, upload_id) else: obj = self.get_object(bucket, key, version_id) # If 'download' is missing from query string it will have # the value None. return self.send_object(bucket, obj, as_attachment=download is not None)
python
def get(self, bucket=None, key=None, version_id=None, upload_id=None, uploads=None, download=None): """Get object or list parts of a multpart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param version_id: The version ID. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :param download: The download flag. (Default: ``None``) :returns: A Flask response. """ if upload_id: return self.multipart_listparts(bucket, key, upload_id) else: obj = self.get_object(bucket, key, version_id) # If 'download' is missing from query string it will have # the value None. return self.send_object(bucket, obj, as_attachment=download is not None)
[ "def", "get", "(", "self", ",", "bucket", "=", "None", ",", "key", "=", "None", ",", "version_id", "=", "None", ",", "upload_id", "=", "None", ",", "uploads", "=", "None", ",", "download", "=", "None", ")", ":", "if", "upload_id", ":", "return", "s...
Get object or list parts of a multpart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param version_id: The version ID. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :param download: The download flag. (Default: ``None``) :returns: A Flask response.
[ "Get", "object", "or", "list", "parts", "of", "a", "multpart", "upload", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L768-L787
train
41,933
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ObjectResource.put
def put(self, bucket=None, key=None, upload_id=None): """Update a new object or upload a part of a multipart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :returns: A Flask response. """ if upload_id is not None: return self.multipart_uploadpart(bucket, key, upload_id) else: return self.create_object(bucket, key)
python
def put(self, bucket=None, key=None, upload_id=None): """Update a new object or upload a part of a multipart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :returns: A Flask response. """ if upload_id is not None: return self.multipart_uploadpart(bucket, key, upload_id) else: return self.create_object(bucket, key)
[ "def", "put", "(", "self", ",", "bucket", "=", "None", ",", "key", "=", "None", ",", "upload_id", "=", "None", ")", ":", "if", "upload_id", "is", "not", "None", ":", "return", "self", ".", "multipart_uploadpart", "(", "bucket", ",", "key", ",", "uplo...
Update a new object or upload a part of a multipart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :returns: A Flask response.
[ "Update", "a", "new", "object", "or", "upload", "a", "part", "of", "a", "multipart", "upload", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L810-L822
train
41,934
inveniosoftware/invenio-files-rest
invenio_files_rest/views.py
ObjectResource.delete
def delete(self, bucket=None, key=None, version_id=None, upload_id=None, uploads=None): """Delete an object or abort a multipart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param version_id: The version ID. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :returns: A Flask response. """ if upload_id is not None: return self.multipart_delete(bucket, key, upload_id) else: obj = self.get_object(bucket, key, version_id) return self.delete_object(bucket, obj, version_id)
python
def delete(self, bucket=None, key=None, version_id=None, upload_id=None, uploads=None): """Delete an object or abort a multipart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param version_id: The version ID. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :returns: A Flask response. """ if upload_id is not None: return self.multipart_delete(bucket, key, upload_id) else: obj = self.get_object(bucket, key, version_id) return self.delete_object(bucket, obj, version_id)
[ "def", "delete", "(", "self", ",", "bucket", "=", "None", ",", "key", "=", "None", ",", "version_id", "=", "None", ",", "upload_id", "=", "None", ",", "uploads", "=", "None", ")", ":", "if", "upload_id", "is", "not", "None", ":", "return", "self", ...
Delete an object or abort a multipart upload. :param bucket: The bucket (instance or id) to get the object from. (Default: ``None``) :param key: The file key. (Default: ``None``) :param version_id: The version ID. (Default: ``None``) :param upload_id: The upload ID. (Default: ``None``) :returns: A Flask response.
[ "Delete", "an", "object", "or", "abort", "a", "multipart", "upload", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/views.py#L826-L841
train
41,935
django-cumulus/django-cumulus
cumulus/authentication.py
Auth._get_container
def _get_container(self): """ Gets or creates the container. """ if not hasattr(self, "_container"): if self.use_pyrax: self._container = self.connection.create_container(self.container_name) else: self._container = None return self._container
python
def _get_container(self): """ Gets or creates the container. """ if not hasattr(self, "_container"): if self.use_pyrax: self._container = self.connection.create_container(self.container_name) else: self._container = None return self._container
[ "def", "_get_container", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_container\"", ")", ":", "if", "self", ".", "use_pyrax", ":", "self", ".", "_container", "=", "self", ".", "connection", ".", "create_container", "(", "self", "....
Gets or creates the container.
[ "Gets", "or", "creates", "the", "container", "." ]
64feb07b857af28f226be4899e875c29405e261d
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/authentication.py#L101-L110
train
41,936
django-cumulus/django-cumulus
cumulus/authentication.py
Auth._get_object
def _get_object(self, name): """ Helper function to retrieve the requested Object. """ if self.use_pyrax: try: return self.container.get_object(name) except pyrax.exceptions.NoSuchObject: return None elif swiftclient: try: return self.container.get_object(name) except swiftclient.exceptions.ClientException: return None else: return self.container.get_object(name)
python
def _get_object(self, name): """ Helper function to retrieve the requested Object. """ if self.use_pyrax: try: return self.container.get_object(name) except pyrax.exceptions.NoSuchObject: return None elif swiftclient: try: return self.container.get_object(name) except swiftclient.exceptions.ClientException: return None else: return self.container.get_object(name)
[ "def", "_get_object", "(", "self", ",", "name", ")", ":", "if", "self", ".", "use_pyrax", ":", "try", ":", "return", "self", ".", "container", ".", "get_object", "(", "name", ")", "except", "pyrax", ".", "exceptions", ".", "NoSuchObject", ":", "return", ...
Helper function to retrieve the requested Object.
[ "Helper", "function", "to", "retrieve", "the", "requested", "Object", "." ]
64feb07b857af28f226be4899e875c29405e261d
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/authentication.py#L157-L172
train
41,937
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
as_object_version
def as_object_version(value): """Get an object version object from an object version ID or an object version. :param value: A :class:`invenio_files_rest.models.ObjectVersion` or an object version ID. :returns: A :class:`invenio_files_rest.models.ObjectVersion` instance. """ return value if isinstance(value, ObjectVersion) \ else ObjectVersion.query.filter_by(version_id=value).one_or_none()
python
def as_object_version(value): """Get an object version object from an object version ID or an object version. :param value: A :class:`invenio_files_rest.models.ObjectVersion` or an object version ID. :returns: A :class:`invenio_files_rest.models.ObjectVersion` instance. """ return value if isinstance(value, ObjectVersion) \ else ObjectVersion.query.filter_by(version_id=value).one_or_none()
[ "def", "as_object_version", "(", "value", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "ObjectVersion", ")", "else", "ObjectVersion", ".", "query", ".", "filter_by", "(", "version_id", "=", "value", ")", ".", "one_or_none", "(", ")" ]
Get an object version object from an object version ID or an object version. :param value: A :class:`invenio_files_rest.models.ObjectVersion` or an object version ID. :returns: A :class:`invenio_files_rest.models.ObjectVersion` instance.
[ "Get", "an", "object", "version", "object", "from", "an", "object", "version", "ID", "or", "an", "object", "version", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L102-L110
train
41,938
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
update_bucket_size
def update_bucket_size(f): """Decorate to update bucket size after operation.""" @wraps(f) def inner(self, *args, **kwargs): res = f(self, *args, **kwargs) self.bucket.size += self.file.size return res return inner
python
def update_bucket_size(f): """Decorate to update bucket size after operation.""" @wraps(f) def inner(self, *args, **kwargs): res = f(self, *args, **kwargs) self.bucket.size += self.file.size return res return inner
[ "def", "update_bucket_size", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "sel...
Decorate to update bucket size after operation.
[ "Decorate", "to", "update", "bucket", "size", "after", "operation", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L126-L133
train
41,939
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ensure_state
def ensure_state(default_getter, exc_class, default_msg=None): """Create a decorator factory function.""" def decorator(getter=default_getter, msg=default_msg): def ensure_decorator(f): @wraps(f) def inner(self, *args, **kwargs): if not getter(self): raise exc_class(msg) if msg else exc_class() return f(self, *args, **kwargs) return inner return ensure_decorator return decorator
python
def ensure_state(default_getter, exc_class, default_msg=None): """Create a decorator factory function.""" def decorator(getter=default_getter, msg=default_msg): def ensure_decorator(f): @wraps(f) def inner(self, *args, **kwargs): if not getter(self): raise exc_class(msg) if msg else exc_class() return f(self, *args, **kwargs) return inner return ensure_decorator return decorator
[ "def", "ensure_state", "(", "default_getter", ",", "exc_class", ",", "default_msg", "=", "None", ")", ":", "def", "decorator", "(", "getter", "=", "default_getter", ",", "msg", "=", "default_msg", ")", ":", "def", "ensure_decorator", "(", "f", ")", ":", "@...
Create a decorator factory function.
[ "Create", "a", "decorator", "factory", "function", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L136-L147
train
41,940
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Location.validate_name
def validate_name(self, key, name): """Validate name.""" if not slug_pattern.match(name) or len(name) > 20: raise ValueError( 'Invalid location name (lower-case alphanumeric + danshes).') return name
python
def validate_name(self, key, name): """Validate name.""" if not slug_pattern.match(name) or len(name) > 20: raise ValueError( 'Invalid location name (lower-case alphanumeric + danshes).') return name
[ "def", "validate_name", "(", "self", ",", "key", ",", "name", ")", ":", "if", "not", "slug_pattern", ".", "match", "(", "name", ")", "or", "len", "(", "name", ")", ">", "20", ":", "raise", "ValueError", "(", "'Invalid location name (lower-case alphanumeric +...
Validate name.
[ "Validate", "name", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L277-L282
train
41,941
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Bucket.size_limit
def size_limit(self): """Get size limit for this bucket. The limit is based on the minimum output of the file size limiters. """ limits = [ lim for lim in current_files_rest.file_size_limiters( self) if lim.limit is not None ] return min(limits) if limits else None
python
def size_limit(self): """Get size limit for this bucket. The limit is based on the minimum output of the file size limiters. """ limits = [ lim for lim in current_files_rest.file_size_limiters( self) if lim.limit is not None ] return min(limits) if limits else None
[ "def", "size_limit", "(", "self", ")", ":", "limits", "=", "[", "lim", "for", "lim", "in", "current_files_rest", ".", "file_size_limiters", "(", "self", ")", "if", "lim", ".", "limit", "is", "not", "None", "]", "return", "min", "(", "limits", ")", "if"...
Get size limit for this bucket. The limit is based on the minimum output of the file size limiters.
[ "Get", "size", "limit", "for", "this", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L397-L407
train
41,942
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Bucket.snapshot
def snapshot(self, lock=False): """Create a snapshot of latest objects in bucket. :param lock: Create the new bucket in a locked state. :returns: Newly created bucket containing copied ObjectVersion. """ with db.session.begin_nested(): bucket = Bucket( default_location=self.default_location, default_storage_class=self.default_storage_class, quota_size=self.quota_size, ) db.session.add(bucket) for o in ObjectVersion.get_by_bucket(self): o.copy(bucket=bucket) bucket.locked = True if lock else self.locked return bucket
python
def snapshot(self, lock=False): """Create a snapshot of latest objects in bucket. :param lock: Create the new bucket in a locked state. :returns: Newly created bucket containing copied ObjectVersion. """ with db.session.begin_nested(): bucket = Bucket( default_location=self.default_location, default_storage_class=self.default_storage_class, quota_size=self.quota_size, ) db.session.add(bucket) for o in ObjectVersion.get_by_bucket(self): o.copy(bucket=bucket) bucket.locked = True if lock else self.locked return bucket
[ "def", "snapshot", "(", "self", ",", "lock", "=", "False", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "bucket", "=", "Bucket", "(", "default_location", "=", "self", ".", "default_location", ",", "default_storage_class", "="...
Create a snapshot of latest objects in bucket. :param lock: Create the new bucket in a locked state. :returns: Newly created bucket containing copied ObjectVersion.
[ "Create", "a", "snapshot", "of", "latest", "objects", "in", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L418-L437
train
41,943
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Bucket.sync
def sync(self, bucket, delete_extras=False): """Sync self bucket ObjectVersions to the destination bucket. The bucket is fully mirrored with the destination bucket following the logic: * same ObjectVersions are not touched * new ObjectVersions are added to destination * deleted ObjectVersions are deleted in destination * extra ObjectVersions in dest are deleted if `delete_extras` param is True :param bucket: The destination bucket. :param delete_extras: Delete extra ObjectVersions in destination if True. :returns: The bucket with an exact copy of ObjectVersions in self. """ assert not bucket.locked src_ovs = ObjectVersion.get_by_bucket(bucket=self, with_deleted=True) dest_ovs = ObjectVersion.get_by_bucket(bucket=bucket, with_deleted=True) # transform into a dict { key: object version } src_keys = {ov.key: ov for ov in src_ovs} dest_keys = {ov.key: ov for ov in dest_ovs} for key, ov in src_keys.items(): if not ov.deleted: if key not in dest_keys or \ ov.file_id != dest_keys[key].file_id: ov.copy(bucket=bucket) elif key in dest_keys and not dest_keys[key].deleted: ObjectVersion.delete(bucket, key) if delete_extras: for key, ov in dest_keys.items(): if key not in src_keys: ObjectVersion.delete(bucket, key) return bucket
python
def sync(self, bucket, delete_extras=False): """Sync self bucket ObjectVersions to the destination bucket. The bucket is fully mirrored with the destination bucket following the logic: * same ObjectVersions are not touched * new ObjectVersions are added to destination * deleted ObjectVersions are deleted in destination * extra ObjectVersions in dest are deleted if `delete_extras` param is True :param bucket: The destination bucket. :param delete_extras: Delete extra ObjectVersions in destination if True. :returns: The bucket with an exact copy of ObjectVersions in self. """ assert not bucket.locked src_ovs = ObjectVersion.get_by_bucket(bucket=self, with_deleted=True) dest_ovs = ObjectVersion.get_by_bucket(bucket=bucket, with_deleted=True) # transform into a dict { key: object version } src_keys = {ov.key: ov for ov in src_ovs} dest_keys = {ov.key: ov for ov in dest_ovs} for key, ov in src_keys.items(): if not ov.deleted: if key not in dest_keys or \ ov.file_id != dest_keys[key].file_id: ov.copy(bucket=bucket) elif key in dest_keys and not dest_keys[key].deleted: ObjectVersion.delete(bucket, key) if delete_extras: for key, ov in dest_keys.items(): if key not in src_keys: ObjectVersion.delete(bucket, key) return bucket
[ "def", "sync", "(", "self", ",", "bucket", ",", "delete_extras", "=", "False", ")", ":", "assert", "not", "bucket", ".", "locked", "src_ovs", "=", "ObjectVersion", ".", "get_by_bucket", "(", "bucket", "=", "self", ",", "with_deleted", "=", "True", ")", "...
Sync self bucket ObjectVersions to the destination bucket. The bucket is fully mirrored with the destination bucket following the logic: * same ObjectVersions are not touched * new ObjectVersions are added to destination * deleted ObjectVersions are deleted in destination * extra ObjectVersions in dest are deleted if `delete_extras` param is True :param bucket: The destination bucket. :param delete_extras: Delete extra ObjectVersions in destination if True. :returns: The bucket with an exact copy of ObjectVersions in self.
[ "Sync", "self", "bucket", "ObjectVersions", "to", "the", "destination", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L440-L479
train
41,944
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Bucket.create
def create(cls, location=None, storage_class=None, **kwargs): r"""Create a bucket. :param location: Location of a bucket (instance or name). Default: Default location. :param storage_class: Storage class of a bucket. Default: Default storage class. :param \**kwargs: Keyword arguments are forwarded to the class :param \**kwargs: Keyword arguments are forwarded to the class constructor. :returns: Created bucket. """ with db.session.begin_nested(): if location is None: location = Location.get_default() elif isinstance(location, six.string_types): location = Location.get_by_name(location) obj = cls( default_location=location.id, default_storage_class=storage_class or current_app.config[ 'FILES_REST_DEFAULT_STORAGE_CLASS'], **kwargs ) db.session.add(obj) return obj
python
def create(cls, location=None, storage_class=None, **kwargs): r"""Create a bucket. :param location: Location of a bucket (instance or name). Default: Default location. :param storage_class: Storage class of a bucket. Default: Default storage class. :param \**kwargs: Keyword arguments are forwarded to the class :param \**kwargs: Keyword arguments are forwarded to the class constructor. :returns: Created bucket. """ with db.session.begin_nested(): if location is None: location = Location.get_default() elif isinstance(location, six.string_types): location = Location.get_by_name(location) obj = cls( default_location=location.id, default_storage_class=storage_class or current_app.config[ 'FILES_REST_DEFAULT_STORAGE_CLASS'], **kwargs ) db.session.add(obj) return obj
[ "def", "create", "(", "cls", ",", "location", "=", "None", ",", "storage_class", "=", "None", ",", "*", "*", "kwargs", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "if", "location", "is", "None", ":", "location", "=", ...
r"""Create a bucket. :param location: Location of a bucket (instance or name). Default: Default location. :param storage_class: Storage class of a bucket. Default: Default storage class. :param \**kwargs: Keyword arguments are forwarded to the class :param \**kwargs: Keyword arguments are forwarded to the class constructor. :returns: Created bucket.
[ "r", "Create", "a", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L486-L511
train
41,945
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
BucketTag.get
def get(cls, bucket, key): """Get tag object.""" return cls.query.filter_by( bucket_id=as_bucket_id(bucket), key=key, ).one_or_none()
python
def get(cls, bucket, key): """Get tag object.""" return cls.query.filter_by( bucket_id=as_bucket_id(bucket), key=key, ).one_or_none()
[ "def", "get", "(", "cls", ",", "bucket", ",", "key", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "bucket_id", "=", "as_bucket_id", "(", "bucket", ")", ",", "key", "=", "key", ",", ")", ".", "one_or_none", "(", ")" ]
Get tag object.
[ "Get", "tag", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L592-L597
train
41,946
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
BucketTag.create
def create(cls, bucket, key, value): """Create a new tag for bucket.""" with db.session.begin_nested(): obj = cls( bucket_id=as_bucket_id(bucket), key=key, value=value ) db.session.add(obj) return obj
python
def create(cls, bucket, key, value): """Create a new tag for bucket.""" with db.session.begin_nested(): obj = cls( bucket_id=as_bucket_id(bucket), key=key, value=value ) db.session.add(obj) return obj
[ "def", "create", "(", "cls", ",", "bucket", ",", "key", ",", "value", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "obj", "=", "cls", "(", "bucket_id", "=", "as_bucket_id", "(", "bucket", ")", ",", "key", "=", "key", ...
Create a new tag for bucket.
[ "Create", "a", "new", "tag", "for", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L600-L609
train
41,947
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
BucketTag.create_or_update
def create_or_update(cls, bucket, key, value): """Create or update a new tag for bucket.""" obj = cls.get(bucket, key) if obj: obj.value = value db.session.merge(obj) else: obj = cls.create(bucket, key, value) return obj
python
def create_or_update(cls, bucket, key, value): """Create or update a new tag for bucket.""" obj = cls.get(bucket, key) if obj: obj.value = value db.session.merge(obj) else: obj = cls.create(bucket, key, value) return obj
[ "def", "create_or_update", "(", "cls", ",", "bucket", ",", "key", ",", "value", ")", ":", "obj", "=", "cls", ".", "get", "(", "bucket", ",", "key", ")", "if", "obj", ":", "obj", ".", "value", "=", "value", "db", ".", "session", ".", "merge", "(",...
Create or update a new tag for bucket.
[ "Create", "or", "update", "a", "new", "tag", "for", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L612-L620
train
41,948
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
BucketTag.get_value
def get_value(cls, bucket, key): """Get tag value.""" obj = cls.get(bucket, key) return obj.value if obj else None
python
def get_value(cls, bucket, key): """Get tag value.""" obj = cls.get(bucket, key) return obj.value if obj else None
[ "def", "get_value", "(", "cls", ",", "bucket", ",", "key", ")", ":", "obj", "=", "cls", ".", "get", "(", "bucket", ",", "key", ")", "return", "obj", ".", "value", "if", "obj", "else", "None" ]
Get tag value.
[ "Get", "tag", "value", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L623-L626
train
41,949
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.validate_uri
def validate_uri(self, key, uri): """Validate uri.""" if len(uri) > current_app.config['FILES_REST_FILE_URI_MAX_LEN']: raise ValueError( 'FileInstance URI too long ({0}).'.format(len(uri))) return uri
python
def validate_uri(self, key, uri): """Validate uri.""" if len(uri) > current_app.config['FILES_REST_FILE_URI_MAX_LEN']: raise ValueError( 'FileInstance URI too long ({0}).'.format(len(uri))) return uri
[ "def", "validate_uri", "(", "self", ",", "key", ",", "uri", ")", ":", "if", "len", "(", "uri", ")", ">", "current_app", ".", "config", "[", "'FILES_REST_FILE_URI_MAX_LEN'", "]", ":", "raise", "ValueError", "(", "'FileInstance URI too long ({0}).'", ".", "forma...
Validate uri.
[ "Validate", "uri", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L695-L700
train
41,950
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.get_by_uri
def get_by_uri(cls, uri): """Get a file instance by URI.""" assert uri is not None return cls.query.filter_by(uri=uri).one_or_none()
python
def get_by_uri(cls, uri): """Get a file instance by URI.""" assert uri is not None return cls.query.filter_by(uri=uri).one_or_none()
[ "def", "get_by_uri", "(", "cls", ",", "uri", ")", ":", "assert", "uri", "is", "not", "None", "return", "cls", ".", "query", ".", "filter_by", "(", "uri", "=", "uri", ")", ".", "one_or_none", "(", ")" ]
Get a file instance by URI.
[ "Get", "a", "file", "instance", "by", "URI", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L708-L711
train
41,951
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.create
def create(cls): """Create a file instance. Note, object is only added to the database session. """ obj = cls( id=uuid.uuid4(), writable=True, readable=False, size=0, ) db.session.add(obj) return obj
python
def create(cls): """Create a file instance. Note, object is only added to the database session. """ obj = cls( id=uuid.uuid4(), writable=True, readable=False, size=0, ) db.session.add(obj) return obj
[ "def", "create", "(", "cls", ")", ":", "obj", "=", "cls", "(", "id", "=", "uuid", ".", "uuid4", "(", ")", ",", "writable", "=", "True", ",", "readable", "=", "False", ",", "size", "=", "0", ",", ")", "db", ".", "session", ".", "add", "(", "ob...
Create a file instance. Note, object is only added to the database session.
[ "Create", "a", "file", "instance", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L714-L726
train
41,952
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.delete
def delete(self): """Delete a file instance. The file instance can be deleted if it has no references from other objects. The caller is responsible to test if the file instance is writable and that the disk file can actually be removed. .. note:: Normally you should use the Celery task to delete a file instance, as this method will not remove the file on disk. """ self.query.filter_by(id=self.id).delete() return self
python
def delete(self): """Delete a file instance. The file instance can be deleted if it has no references from other objects. The caller is responsible to test if the file instance is writable and that the disk file can actually be removed. .. note:: Normally you should use the Celery task to delete a file instance, as this method will not remove the file on disk. """ self.query.filter_by(id=self.id).delete() return self
[ "def", "delete", "(", "self", ")", ":", "self", ".", "query", ".", "filter_by", "(", "id", "=", "self", ".", "id", ")", ".", "delete", "(", ")", "return", "self" ]
Delete a file instance. The file instance can be deleted if it has no references from other objects. The caller is responsible to test if the file instance is writable and that the disk file can actually be removed. .. note:: Normally you should use the Celery task to delete a file instance, as this method will not remove the file on disk.
[ "Delete", "a", "file", "instance", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L728-L741
train
41,953
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.update_checksum
def update_checksum(self, progress_callback=None, chunk_size=None, checksum_kwargs=None, **kwargs): """Update checksum based on file.""" self.checksum = self.storage(**kwargs).checksum( progress_callback=progress_callback, chunk_size=chunk_size, **(checksum_kwargs or {}))
python
def update_checksum(self, progress_callback=None, chunk_size=None, checksum_kwargs=None, **kwargs): """Update checksum based on file.""" self.checksum = self.storage(**kwargs).checksum( progress_callback=progress_callback, chunk_size=chunk_size, **(checksum_kwargs or {}))
[ "def", "update_checksum", "(", "self", ",", "progress_callback", "=", "None", ",", "chunk_size", "=", "None", ",", "checksum_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "checksum", "=", "self", ".", "storage", "(", "*", "*", "...
Update checksum based on file.
[ "Update", "checksum", "based", "on", "file", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L754-L759
train
41,954
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.clear_last_check
def clear_last_check(self): """Clear the checksum of the file.""" with db.session.begin_nested(): self.last_check = None self.last_check_at = datetime.utcnow() return self
python
def clear_last_check(self): """Clear the checksum of the file.""" with db.session.begin_nested(): self.last_check = None self.last_check_at = datetime.utcnow() return self
[ "def", "clear_last_check", "(", "self", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "self", ".", "last_check", "=", "None", "self", ".", "last_check_at", "=", "datetime", ".", "utcnow", "(", ")", "return", "self" ]
Clear the checksum of the file.
[ "Clear", "the", "checksum", "of", "the", "file", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L761-L766
train
41,955
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.verify_checksum
def verify_checksum(self, progress_callback=None, chunk_size=None, throws=True, checksum_kwargs=None, **kwargs): """Verify checksum of file instance. :param bool throws: If `True`, exceptions raised during checksum calculation will be re-raised after logging. If set to `False`, and an exception occurs, the `last_check` field is set to `None` (`last_check_at` of course is updated), since no check actually was performed. :param dict checksum_kwargs: Passed as `**kwargs`` to ``storage().checksum``. """ try: real_checksum = self.storage(**kwargs).checksum( progress_callback=progress_callback, chunk_size=chunk_size, **(checksum_kwargs or {})) except Exception as exc: current_app.logger.exception(str(exc)) if throws: raise real_checksum = None with db.session.begin_nested(): self.last_check = (None if real_checksum is None else (self.checksum == real_checksum)) self.last_check_at = datetime.utcnow() return self.last_check
python
def verify_checksum(self, progress_callback=None, chunk_size=None, throws=True, checksum_kwargs=None, **kwargs): """Verify checksum of file instance. :param bool throws: If `True`, exceptions raised during checksum calculation will be re-raised after logging. If set to `False`, and an exception occurs, the `last_check` field is set to `None` (`last_check_at` of course is updated), since no check actually was performed. :param dict checksum_kwargs: Passed as `**kwargs`` to ``storage().checksum``. """ try: real_checksum = self.storage(**kwargs).checksum( progress_callback=progress_callback, chunk_size=chunk_size, **(checksum_kwargs or {})) except Exception as exc: current_app.logger.exception(str(exc)) if throws: raise real_checksum = None with db.session.begin_nested(): self.last_check = (None if real_checksum is None else (self.checksum == real_checksum)) self.last_check_at = datetime.utcnow() return self.last_check
[ "def", "verify_checksum", "(", "self", ",", "progress_callback", "=", "None", ",", "chunk_size", "=", "None", ",", "throws", "=", "True", ",", "checksum_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "real_checksum", "=", "self", "....
Verify checksum of file instance. :param bool throws: If `True`, exceptions raised during checksum calculation will be re-raised after logging. If set to `False`, and an exception occurs, the `last_check` field is set to `None` (`last_check_at` of course is updated), since no check actually was performed. :param dict checksum_kwargs: Passed as `**kwargs`` to ``storage().checksum``.
[ "Verify", "checksum", "of", "file", "instance", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L768-L793
train
41,956
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.init_contents
def init_contents(self, size=0, **kwargs): """Initialize file.""" self.set_uri( *self.storage(**kwargs).initialize(size=size), readable=False, writable=True)
python
def init_contents(self, size=0, **kwargs): """Initialize file.""" self.set_uri( *self.storage(**kwargs).initialize(size=size), readable=False, writable=True)
[ "def", "init_contents", "(", "self", ",", "size", "=", "0", ",", "*", "*", "kwargs", ")", ":", "self", ".", "set_uri", "(", "*", "self", ".", "storage", "(", "*", "*", "kwargs", ")", ".", "initialize", "(", "size", "=", "size", ")", ",", "readabl...
Initialize file.
[ "Initialize", "file", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L796-L800
train
41,957
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.copy_contents
def copy_contents(self, fileinstance, progress_callback=None, chunk_size=None, **kwargs): """Copy this file instance into another file instance.""" if not fileinstance.readable: raise ValueError('Source file instance is not readable.') if not self.size == 0: raise ValueError('File instance has data.') self.set_uri( *self.storage(**kwargs).copy( fileinstance.storage(**kwargs), chunk_size=chunk_size, progress_callback=progress_callback))
python
def copy_contents(self, fileinstance, progress_callback=None, chunk_size=None, **kwargs): """Copy this file instance into another file instance.""" if not fileinstance.readable: raise ValueError('Source file instance is not readable.') if not self.size == 0: raise ValueError('File instance has data.') self.set_uri( *self.storage(**kwargs).copy( fileinstance.storage(**kwargs), chunk_size=chunk_size, progress_callback=progress_callback))
[ "def", "copy_contents", "(", "self", ",", "fileinstance", ",", "progress_callback", "=", "None", ",", "chunk_size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "fileinstance", ".", "readable", ":", "raise", "ValueError", "(", "'Source file i...
Copy this file instance into another file instance.
[ "Copy", "this", "file", "instance", "into", "another", "file", "instance", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L832-L844
train
41,958
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
FileInstance.set_uri
def set_uri(self, uri, size, checksum, readable=True, writable=False, storage_class=None): """Set a location of a file.""" self.uri = uri self.size = size self.checksum = checksum self.writable = writable self.readable = readable self.storage_class = \ current_app.config['FILES_REST_DEFAULT_STORAGE_CLASS'] \ if storage_class is None else \ storage_class return self
python
def set_uri(self, uri, size, checksum, readable=True, writable=False, storage_class=None): """Set a location of a file.""" self.uri = uri self.size = size self.checksum = checksum self.writable = writable self.readable = readable self.storage_class = \ current_app.config['FILES_REST_DEFAULT_STORAGE_CLASS'] \ if storage_class is None else \ storage_class return self
[ "def", "set_uri", "(", "self", ",", "uri", ",", "size", ",", "checksum", ",", "readable", "=", "True", ",", "writable", "=", "False", ",", "storage_class", "=", "None", ")", ":", "self", ".", "uri", "=", "uri", "self", ".", "size", "=", "size", "se...
Set a location of a file.
[ "Set", "a", "location", "of", "a", "file", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L861-L873
train
41,959
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersion.set_contents
def set_contents(self, stream, chunk_size=None, size=None, size_limit=None, progress_callback=None): """Save contents of stream to file instance. If a file instance has already been set, this methods raises an ``FileInstanceAlreadySetError`` exception. :param stream: File-like stream. :param size: Size of stream if known. :param chunk_size: Desired chunk size to read stream in. It is up to the storage interface if it respects this value. """ if size_limit is None: size_limit = self.bucket.size_limit self.file = FileInstance.create() self.file.set_contents( stream, size_limit=size_limit, size=size, chunk_size=chunk_size, progress_callback=progress_callback, default_location=self.bucket.location.uri, default_storage_class=self.bucket.default_storage_class, ) return self
python
def set_contents(self, stream, chunk_size=None, size=None, size_limit=None, progress_callback=None): """Save contents of stream to file instance. If a file instance has already been set, this methods raises an ``FileInstanceAlreadySetError`` exception. :param stream: File-like stream. :param size: Size of stream if known. :param chunk_size: Desired chunk size to read stream in. It is up to the storage interface if it respects this value. """ if size_limit is None: size_limit = self.bucket.size_limit self.file = FileInstance.create() self.file.set_contents( stream, size_limit=size_limit, size=size, chunk_size=chunk_size, progress_callback=progress_callback, default_location=self.bucket.location.uri, default_storage_class=self.bucket.default_storage_class, ) return self
[ "def", "set_contents", "(", "self", ",", "stream", ",", "chunk_size", "=", "None", ",", "size", "=", "None", ",", "size_limit", "=", "None", ",", "progress_callback", "=", "None", ")", ":", "if", "size_limit", "is", "None", ":", "size_limit", "=", "self"...
Save contents of stream to file instance. If a file instance has already been set, this methods raises an ``FileInstanceAlreadySetError`` exception. :param stream: File-like stream. :param size: Size of stream if known. :param chunk_size: Desired chunk size to read stream in. It is up to the storage interface if it respects this value.
[ "Save", "contents", "of", "stream", "to", "file", "instance", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L979-L1002
train
41,960
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersion.set_location
def set_location(self, uri, size, checksum, storage_class=None): """Set only URI location of for object. Useful to link files on externally controlled storage. If a file instance has already been set, this methods raises an ``FileInstanceAlreadySetError`` exception. :param uri: Full URI to object (which can be interpreted by the storage interface). :param size: Size of file. :param checksum: Checksum of file. :param storage_class: Storage class where file is stored () """ self.file = FileInstance() self.file.set_uri( uri, size, checksum, storage_class=storage_class ) db.session.add(self.file) return self
python
def set_location(self, uri, size, checksum, storage_class=None): """Set only URI location of for object. Useful to link files on externally controlled storage. If a file instance has already been set, this methods raises an ``FileInstanceAlreadySetError`` exception. :param uri: Full URI to object (which can be interpreted by the storage interface). :param size: Size of file. :param checksum: Checksum of file. :param storage_class: Storage class where file is stored () """ self.file = FileInstance() self.file.set_uri( uri, size, checksum, storage_class=storage_class ) db.session.add(self.file) return self
[ "def", "set_location", "(", "self", ",", "uri", ",", "size", ",", "checksum", ",", "storage_class", "=", "None", ")", ":", "self", ".", "file", "=", "FileInstance", "(", ")", "self", ".", "file", ".", "set_uri", "(", "uri", ",", "size", ",", "checksu...
Set only URI location of for object. Useful to link files on externally controlled storage. If a file instance has already been set, this methods raises an ``FileInstanceAlreadySetError`` exception. :param uri: Full URI to object (which can be interpreted by the storage interface). :param size: Size of file. :param checksum: Checksum of file. :param storage_class: Storage class where file is stored ()
[ "Set", "only", "URI", "location", "of", "for", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1006-L1024
train
41,961
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersion.send_file
def send_file(self, restricted=True, trusted=False, **kwargs): """Wrap around FileInstance's send file.""" return self.file.send_file( self.basename, restricted=restricted, mimetype=self.mimetype, trusted=trusted, **kwargs )
python
def send_file(self, restricted=True, trusted=False, **kwargs): """Wrap around FileInstance's send file.""" return self.file.send_file( self.basename, restricted=restricted, mimetype=self.mimetype, trusted=trusted, **kwargs )
[ "def", "send_file", "(", "self", ",", "restricted", "=", "True", ",", "trusted", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "file", ".", "send_file", "(", "self", ".", "basename", ",", "restricted", "=", "restricted", ",", ...
Wrap around FileInstance's send file.
[ "Wrap", "around", "FileInstance", "s", "send", "file", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1033-L1041
train
41,962
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersion.copy
def copy(self, bucket=None, key=None): """Copy an object version to a given bucket + object key. The copy operation is handled completely at the metadata level. The actual data on disk is not copied. Instead, the two object versions will point to the same physical file (via the same FileInstance). All the tags associated with the current object version are copied over to the new instance. .. warning:: If the destination object exists, it will be replaced by the new object version which will become the latest version. :param bucket: The bucket (instance or id) to copy the object to. Default: current bucket. :param key: Key name of destination object. Default: current object key. :returns: The copied object version. """ new_ob = ObjectVersion.create( self.bucket if bucket is None else as_bucket(bucket), key or self.key, _file_id=self.file_id ) for tag in self.tags: ObjectVersionTag.create_or_update(object_version=new_ob, key=tag.key, value=tag.value) return new_ob
python
def copy(self, bucket=None, key=None): """Copy an object version to a given bucket + object key. The copy operation is handled completely at the metadata level. The actual data on disk is not copied. Instead, the two object versions will point to the same physical file (via the same FileInstance). All the tags associated with the current object version are copied over to the new instance. .. warning:: If the destination object exists, it will be replaced by the new object version which will become the latest version. :param bucket: The bucket (instance or id) to copy the object to. Default: current bucket. :param key: Key name of destination object. Default: current object key. :returns: The copied object version. """ new_ob = ObjectVersion.create( self.bucket if bucket is None else as_bucket(bucket), key or self.key, _file_id=self.file_id ) for tag in self.tags: ObjectVersionTag.create_or_update(object_version=new_ob, key=tag.key, value=tag.value) return new_ob
[ "def", "copy", "(", "self", ",", "bucket", "=", "None", ",", "key", "=", "None", ")", ":", "new_ob", "=", "ObjectVersion", ".", "create", "(", "self", ".", "bucket", "if", "bucket", "is", "None", "else", "as_bucket", "(", "bucket", ")", ",", "key", ...
Copy an object version to a given bucket + object key. The copy operation is handled completely at the metadata level. The actual data on disk is not copied. Instead, the two object versions will point to the same physical file (via the same FileInstance). All the tags associated with the current object version are copied over to the new instance. .. warning:: If the destination object exists, it will be replaced by the new object version which will become the latest version. :param bucket: The bucket (instance or id) to copy the object to. Default: current bucket. :param key: Key name of destination object. Default: current object key. :returns: The copied object version.
[ "Copy", "an", "object", "version", "to", "a", "given", "bucket", "+", "object", "key", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1054-L1086
train
41,963
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersion.remove
def remove(self): """Permanently remove a specific object version from the database. .. warning:: This by-passes the normal versioning and should only be used when you want to permanently delete a specific object version. Otherwise use :py:data:`ObjectVersion.delete()`. Note the method does not remove the associated file instance which must be garbage collected. :returns: ``self``. """ with db.session.begin_nested(): if self.file_id: self.bucket.size -= self.file.size self.query.filter_by( bucket_id=self.bucket_id, key=self.key, version_id=self.version_id, ).delete() return self
python
def remove(self): """Permanently remove a specific object version from the database. .. warning:: This by-passes the normal versioning and should only be used when you want to permanently delete a specific object version. Otherwise use :py:data:`ObjectVersion.delete()`. Note the method does not remove the associated file instance which must be garbage collected. :returns: ``self``. """ with db.session.begin_nested(): if self.file_id: self.bucket.size -= self.file.size self.query.filter_by( bucket_id=self.bucket_id, key=self.key, version_id=self.version_id, ).delete() return self
[ "def", "remove", "(", "self", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "if", "self", ".", "file_id", ":", "self", ".", "bucket", ".", "size", "-=", "self", ".", "file", ".", "size", "self", ".", "query", ".", "f...
Permanently remove a specific object version from the database. .. warning:: This by-passes the normal versioning and should only be used when you want to permanently delete a specific object version. Otherwise use :py:data:`ObjectVersion.delete()`. Note the method does not remove the associated file instance which must be garbage collected. :returns: ``self``.
[ "Permanently", "remove", "a", "specific", "object", "version", "from", "the", "database", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1089-L1112
train
41,964
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersion.get
def get(cls, bucket, key, version_id=None): """Fetch a specific object. By default the latest object version is returned, if ``version_id`` is not set. :param bucket: The bucket (instance or id) to get the object from. :param key: Key of object. :param version_id: Specific version of an object. """ filters = [ cls.bucket_id == as_bucket_id(bucket), cls.key == key, ] if version_id: filters.append(cls.version_id == version_id) else: filters.append(cls.is_head.is_(True)) filters.append(cls.file_id.isnot(None)) return cls.query.filter(*filters).one_or_none()
python
def get(cls, bucket, key, version_id=None): """Fetch a specific object. By default the latest object version is returned, if ``version_id`` is not set. :param bucket: The bucket (instance or id) to get the object from. :param key: Key of object. :param version_id: Specific version of an object. """ filters = [ cls.bucket_id == as_bucket_id(bucket), cls.key == key, ] if version_id: filters.append(cls.version_id == version_id) else: filters.append(cls.is_head.is_(True)) filters.append(cls.file_id.isnot(None)) return cls.query.filter(*filters).one_or_none()
[ "def", "get", "(", "cls", ",", "bucket", ",", "key", ",", "version_id", "=", "None", ")", ":", "filters", "=", "[", "cls", ".", "bucket_id", "==", "as_bucket_id", "(", "bucket", ")", ",", "cls", ".", "key", "==", "key", ",", "]", "if", "version_id"...
Fetch a specific object. By default the latest object version is returned, if ``version_id`` is not set. :param bucket: The bucket (instance or id) to get the object from. :param key: Key of object. :param version_id: Specific version of an object.
[ "Fetch", "a", "specific", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1162-L1183
train
41,965
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersion.get_versions
def get_versions(cls, bucket, key, desc=True): """Fetch all versions of a specific object. :param bucket: The bucket (instance or id) to get the object from. :param key: Key of object. :param desc: Sort results desc if True, asc otherwise. :returns: The query to execute to fetch all versions. """ filters = [ cls.bucket_id == as_bucket_id(bucket), cls.key == key, ] order = cls.created.desc() if desc else cls.created.asc() return cls.query.filter(*filters).order_by(cls.key, order)
python
def get_versions(cls, bucket, key, desc=True): """Fetch all versions of a specific object. :param bucket: The bucket (instance or id) to get the object from. :param key: Key of object. :param desc: Sort results desc if True, asc otherwise. :returns: The query to execute to fetch all versions. """ filters = [ cls.bucket_id == as_bucket_id(bucket), cls.key == key, ] order = cls.created.desc() if desc else cls.created.asc() return cls.query.filter(*filters).order_by(cls.key, order)
[ "def", "get_versions", "(", "cls", ",", "bucket", ",", "key", ",", "desc", "=", "True", ")", ":", "filters", "=", "[", "cls", ".", "bucket_id", "==", "as_bucket_id", "(", "bucket", ")", ",", "cls", ".", "key", "==", "key", ",", "]", "order", "=", ...
Fetch all versions of a specific object. :param bucket: The bucket (instance or id) to get the object from. :param key: Key of object. :param desc: Sort results desc if True, asc otherwise. :returns: The query to execute to fetch all versions.
[ "Fetch", "all", "versions", "of", "a", "specific", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1186-L1201
train
41,966
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersion.get_by_bucket
def get_by_bucket(cls, bucket, versions=False, with_deleted=False): """Return query that fetches all the objects in a bucket. :param bucket: The bucket (instance or id) to query. :param versions: Select all versions if True, only heads otherwise. :param with_deleted: Select also deleted objects if True. :returns: The query to retrieve filtered objects in the given bucket. """ bucket_id = bucket.id if isinstance(bucket, Bucket) else bucket filters = [ cls.bucket_id == bucket_id, ] if not versions: filters.append(cls.is_head.is_(True)) if not with_deleted: filters.append(cls.file_id.isnot(None)) return cls.query.filter(*filters).order_by(cls.key, cls.created.desc())
python
def get_by_bucket(cls, bucket, versions=False, with_deleted=False): """Return query that fetches all the objects in a bucket. :param bucket: The bucket (instance or id) to query. :param versions: Select all versions if True, only heads otherwise. :param with_deleted: Select also deleted objects if True. :returns: The query to retrieve filtered objects in the given bucket. """ bucket_id = bucket.id if isinstance(bucket, Bucket) else bucket filters = [ cls.bucket_id == bucket_id, ] if not versions: filters.append(cls.is_head.is_(True)) if not with_deleted: filters.append(cls.file_id.isnot(None)) return cls.query.filter(*filters).order_by(cls.key, cls.created.desc())
[ "def", "get_by_bucket", "(", "cls", ",", "bucket", ",", "versions", "=", "False", ",", "with_deleted", "=", "False", ")", ":", "bucket_id", "=", "bucket", ".", "id", "if", "isinstance", "(", "bucket", ",", "Bucket", ")", "else", "bucket", "filters", "=",...
Return query that fetches all the objects in a bucket. :param bucket: The bucket (instance or id) to query. :param versions: Select all versions if True, only heads otherwise. :param with_deleted: Select also deleted objects if True. :returns: The query to retrieve filtered objects in the given bucket.
[ "Return", "query", "that", "fetches", "all", "the", "objects", "in", "a", "bucket", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1222-L1242
train
41,967
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersionTag.copy
def copy(self, object_version=None, key=None): """Copy a tag to a given object version. :param object_version: The object version instance to copy the tag to. Default: current object version. :param key: Key of destination tag. Default: current tag key. :return: The copied object version tag. """ return ObjectVersionTag.create( self.object_version if object_version is None else object_version, key or self.key, self.value )
python
def copy(self, object_version=None, key=None): """Copy a tag to a given object version. :param object_version: The object version instance to copy the tag to. Default: current object version. :param key: Key of destination tag. Default: current tag key. :return: The copied object version tag. """ return ObjectVersionTag.create( self.object_version if object_version is None else object_version, key or self.key, self.value )
[ "def", "copy", "(", "self", ",", "object_version", "=", "None", ",", "key", "=", "None", ")", ":", "return", "ObjectVersionTag", ".", "create", "(", "self", ".", "object_version", "if", "object_version", "is", "None", "else", "object_version", ",", "key", ...
Copy a tag to a given object version. :param object_version: The object version instance to copy the tag to. Default: current object version. :param key: Key of destination tag. Default: current tag key. :return: The copied object version tag.
[ "Copy", "a", "tag", "to", "a", "given", "object", "version", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1298-L1311
train
41,968
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersionTag.get
def get(cls, object_version, key): """Get the tag object.""" return cls.query.filter_by( version_id=as_object_version_id(object_version), key=key, ).one_or_none()
python
def get(cls, object_version, key): """Get the tag object.""" return cls.query.filter_by( version_id=as_object_version_id(object_version), key=key, ).one_or_none()
[ "def", "get", "(", "cls", ",", "object_version", ",", "key", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "version_id", "=", "as_object_version_id", "(", "object_version", ")", ",", "key", "=", "key", ",", ")", ".", "one_or_none", "(",...
Get the tag object.
[ "Get", "the", "tag", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1314-L1319
train
41,969
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersionTag.create
def create(cls, object_version, key, value): """Create a new tag for a given object version.""" assert len(key) < 256 assert len(value) < 256 with db.session.begin_nested(): obj = cls(version_id=as_object_version_id(object_version), key=key, value=value) db.session.add(obj) return obj
python
def create(cls, object_version, key, value): """Create a new tag for a given object version.""" assert len(key) < 256 assert len(value) < 256 with db.session.begin_nested(): obj = cls(version_id=as_object_version_id(object_version), key=key, value=value) db.session.add(obj) return obj
[ "def", "create", "(", "cls", ",", "object_version", ",", "key", ",", "value", ")", ":", "assert", "len", "(", "key", ")", "<", "256", "assert", "len", "(", "value", ")", "<", "256", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", ...
Create a new tag for a given object version.
[ "Create", "a", "new", "tag", "for", "a", "given", "object", "version", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1322-L1331
train
41,970
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersionTag.create_or_update
def create_or_update(cls, object_version, key, value): """Create or update a new tag for a given object version.""" assert len(key) < 256 assert len(value) < 256 obj = cls.get(object_version, key) if obj: obj.value = value db.session.merge(obj) else: obj = cls.create(object_version, key, value) return obj
python
def create_or_update(cls, object_version, key, value): """Create or update a new tag for a given object version.""" assert len(key) < 256 assert len(value) < 256 obj = cls.get(object_version, key) if obj: obj.value = value db.session.merge(obj) else: obj = cls.create(object_version, key, value) return obj
[ "def", "create_or_update", "(", "cls", ",", "object_version", ",", "key", ",", "value", ")", ":", "assert", "len", "(", "key", ")", "<", "256", "assert", "len", "(", "value", ")", "<", "256", "obj", "=", "cls", ".", "get", "(", "object_version", ",",...
Create or update a new tag for a given object version.
[ "Create", "or", "update", "a", "new", "tag", "for", "a", "given", "object", "version", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1334-L1344
train
41,971
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersionTag.get_value
def get_value(cls, object_version, key): """Get the tag value.""" obj = cls.get(object_version, key) return obj.value if obj else None
python
def get_value(cls, object_version, key): """Get the tag value.""" obj = cls.get(object_version, key) return obj.value if obj else None
[ "def", "get_value", "(", "cls", ",", "object_version", ",", "key", ")", ":", "obj", "=", "cls", ".", "get", "(", "object_version", ",", "key", ")", "return", "obj", ".", "value", "if", "obj", "else", "None" ]
Get the tag value.
[ "Get", "the", "tag", "value", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1347-L1350
train
41,972
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
ObjectVersionTag.delete
def delete(cls, object_version, key=None): """Delete tags. :param object_version: The object version instance or id. :param key: Key of the tag to delete. Default: delete all tags. """ with db.session.begin_nested(): q = cls.query.filter_by( version_id=as_object_version_id(object_version)) if key: q = q.filter_by(key=key) q.delete()
python
def delete(cls, object_version, key=None): """Delete tags. :param object_version: The object version instance or id. :param key: Key of the tag to delete. Default: delete all tags. """ with db.session.begin_nested(): q = cls.query.filter_by( version_id=as_object_version_id(object_version)) if key: q = q.filter_by(key=key) q.delete()
[ "def", "delete", "(", "cls", ",", "object_version", ",", "key", "=", "None", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "q", "=", "cls", ".", "query", ".", "filter_by", "(", "version_id", "=", "as_object_version_id", "(...
Delete tags. :param object_version: The object version instance or id. :param key: Key of the tag to delete. Default: delete all tags.
[ "Delete", "tags", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1353-L1365
train
41,973
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
MultipartObject.last_part_number
def last_part_number(self): """Get last part number.""" return int(self.size / self.chunk_size) \ if self.size % self.chunk_size else \ int(self.size / self.chunk_size) - 1
python
def last_part_number(self): """Get last part number.""" return int(self.size / self.chunk_size) \ if self.size % self.chunk_size else \ int(self.size / self.chunk_size) - 1
[ "def", "last_part_number", "(", "self", ")", ":", "return", "int", "(", "self", ".", "size", "/", "self", ".", "chunk_size", ")", "if", "self", ".", "size", "%", "self", ".", "chunk_size", "else", "int", "(", "self", ".", "size", "/", "self", ".", ...
Get last part number.
[ "Get", "last", "part", "number", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1435-L1439
train
41,974
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
MultipartObject.is_valid_chunksize
def is_valid_chunksize(chunk_size): """Check if size is valid.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MAX'] return chunk_size >= min_csize and chunk_size <= max_csize
python
def is_valid_chunksize(chunk_size): """Check if size is valid.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MAX'] return chunk_size >= min_csize and chunk_size <= max_csize
[ "def", "is_valid_chunksize", "(", "chunk_size", ")", ":", "min_csize", "=", "current_app", ".", "config", "[", "'FILES_REST_MULTIPART_CHUNKSIZE_MIN'", "]", "max_csize", "=", "current_app", ".", "config", "[", "'FILES_REST_MULTIPART_CHUNKSIZE_MAX'", "]", "return", "chunk...
Check if size is valid.
[ "Check", "if", "size", "is", "valid", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1452-L1456
train
41,975
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
MultipartObject.is_valid_size
def is_valid_size(size, chunk_size): """Validate max theoretical size.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_size = \ chunk_size * current_app.config['FILES_REST_MULTIPART_MAX_PARTS'] return size > min_csize and size <= max_size
python
def is_valid_size(size, chunk_size): """Validate max theoretical size.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_size = \ chunk_size * current_app.config['FILES_REST_MULTIPART_MAX_PARTS'] return size > min_csize and size <= max_size
[ "def", "is_valid_size", "(", "size", ",", "chunk_size", ")", ":", "min_csize", "=", "current_app", ".", "config", "[", "'FILES_REST_MULTIPART_CHUNKSIZE_MIN'", "]", "max_size", "=", "chunk_size", "*", "current_app", ".", "config", "[", "'FILES_REST_MULTIPART_MAX_PARTS'...
Validate max theoretical size.
[ "Validate", "max", "theoretical", "size", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1459-L1464
train
41,976
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
MultipartObject.expected_part_size
def expected_part_size(self, part_number): """Get expected part size for a particular part number.""" last_part = self.multipart.last_part_number if part_number == last_part: return self.multipart.last_part_size elif part_number >= 0 and part_number < last_part: return self.multipart.chunk_size else: raise MultipartInvalidPartNumber()
python
def expected_part_size(self, part_number): """Get expected part size for a particular part number.""" last_part = self.multipart.last_part_number if part_number == last_part: return self.multipart.last_part_size elif part_number >= 0 and part_number < last_part: return self.multipart.chunk_size else: raise MultipartInvalidPartNumber()
[ "def", "expected_part_size", "(", "self", ",", "part_number", ")", ":", "last_part", "=", "self", ".", "multipart", ".", "last_part_number", "if", "part_number", "==", "last_part", ":", "return", "self", ".", "multipart", ".", "last_part_size", "elif", "part_num...
Get expected part size for a particular part number.
[ "Get", "expected", "part", "size", "for", "a", "particular", "part", "number", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1466-L1475
train
41,977
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
MultipartObject.complete
def complete(self): """Mark a multipart object as complete.""" if Part.count(self) != self.last_part_number + 1: raise MultipartMissingParts() with db.session.begin_nested(): self.completed = True self.file.readable = True self.file.writable = False return self
python
def complete(self): """Mark a multipart object as complete.""" if Part.count(self) != self.last_part_number + 1: raise MultipartMissingParts() with db.session.begin_nested(): self.completed = True self.file.readable = True self.file.writable = False return self
[ "def", "complete", "(", "self", ")", ":", "if", "Part", ".", "count", "(", "self", ")", "!=", "self", ".", "last_part_number", "+", "1", ":", "raise", "MultipartMissingParts", "(", ")", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", ...
Mark a multipart object as complete.
[ "Mark", "a", "multipart", "object", "as", "complete", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1478-L1487
train
41,978
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
MultipartObject.merge_parts
def merge_parts(self, version_id=None, **kwargs): """Merge parts into object version.""" self.file.update_checksum(**kwargs) with db.session.begin_nested(): obj = ObjectVersion.create( self.bucket, self.key, _file_id=self.file_id, version_id=version_id ) self.delete() return obj
python
def merge_parts(self, version_id=None, **kwargs): """Merge parts into object version.""" self.file.update_checksum(**kwargs) with db.session.begin_nested(): obj = ObjectVersion.create( self.bucket, self.key, _file_id=self.file_id, version_id=version_id ) self.delete() return obj
[ "def", "merge_parts", "(", "self", ",", "version_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "file", ".", "update_checksum", "(", "*", "*", "kwargs", ")", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "obj", ...
Merge parts into object version.
[ "Merge", "parts", "into", "object", "version", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1490-L1501
train
41,979
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
MultipartObject.delete
def delete(self): """Delete a multipart object.""" # Update bucket size. self.bucket.size -= self.size # Remove parts Part.query_by_multipart(self).delete() # Remove self self.query.filter_by(upload_id=self.upload_id).delete()
python
def delete(self): """Delete a multipart object.""" # Update bucket size. self.bucket.size -= self.size # Remove parts Part.query_by_multipart(self).delete() # Remove self self.query.filter_by(upload_id=self.upload_id).delete()
[ "def", "delete", "(", "self", ")", ":", "# Update bucket size.", "self", ".", "bucket", ".", "size", "-=", "self", ".", "size", "# Remove parts", "Part", ".", "query_by_multipart", "(", "self", ")", ".", "delete", "(", ")", "# Remove self", "self", ".", "q...
Delete a multipart object.
[ "Delete", "a", "multipart", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1503-L1510
train
41,980
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
MultipartObject.get
def get(cls, bucket, key, upload_id, with_completed=False): """Fetch a specific multipart object.""" q = cls.query.filter_by( upload_id=upload_id, bucket_id=as_bucket_id(bucket), key=key, ) if not with_completed: q = q.filter(cls.completed.is_(False)) return q.one_or_none()
python
def get(cls, bucket, key, upload_id, with_completed=False): """Fetch a specific multipart object.""" q = cls.query.filter_by( upload_id=upload_id, bucket_id=as_bucket_id(bucket), key=key, ) if not with_completed: q = q.filter(cls.completed.is_(False)) return q.one_or_none()
[ "def", "get", "(", "cls", ",", "bucket", ",", "key", ",", "upload_id", ",", "with_completed", "=", "False", ")", ":", "q", "=", "cls", ".", "query", ".", "filter_by", "(", "upload_id", "=", "upload_id", ",", "bucket_id", "=", "as_bucket_id", "(", "buck...
Fetch a specific multipart object.
[ "Fetch", "a", "specific", "multipart", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1557-L1567
train
41,981
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Part.end_byte
def end_byte(self): """Get end byte in file for this part.""" return min( (self.part_number + 1) * self.multipart.chunk_size, self.multipart.size )
python
def end_byte(self): """Get end byte in file for this part.""" return min( (self.part_number + 1) * self.multipart.chunk_size, self.multipart.size )
[ "def", "end_byte", "(", "self", ")", ":", "return", "min", "(", "(", "self", ".", "part_number", "+", "1", ")", "*", "self", ".", "multipart", ".", "chunk_size", ",", "self", ".", "multipart", ".", "size", ")" ]
Get end byte in file for this part.
[ "Get", "end", "byte", "in", "file", "for", "this", "part", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1611-L1616
train
41,982
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Part.create
def create(cls, mp, part_number, stream=None, **kwargs): """Create a new part object in a multipart object.""" if part_number < 0 or part_number > mp.last_part_number: raise MultipartInvalidPartNumber() with db.session.begin_nested(): obj = cls( multipart=mp, part_number=part_number, ) db.session.add(obj) if stream: obj.set_contents(stream, **kwargs) return obj
python
def create(cls, mp, part_number, stream=None, **kwargs): """Create a new part object in a multipart object.""" if part_number < 0 or part_number > mp.last_part_number: raise MultipartInvalidPartNumber() with db.session.begin_nested(): obj = cls( multipart=mp, part_number=part_number, ) db.session.add(obj) if stream: obj.set_contents(stream, **kwargs) return obj
[ "def", "create", "(", "cls", ",", "mp", ",", "part_number", ",", "stream", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "part_number", "<", "0", "or", "part_number", ">", "mp", ".", "last_part_number", ":", "raise", "MultipartInvalidPartNumber", ...
Create a new part object in a multipart object.
[ "Create", "a", "new", "part", "object", "in", "a", "multipart", "object", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1624-L1637
train
41,983
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Part.get_or_create
def get_or_create(cls, mp, part_number): """Get or create a part.""" obj = cls.get_or_none(mp, part_number) if obj: return obj return cls.create(mp, part_number)
python
def get_or_create(cls, mp, part_number): """Get or create a part.""" obj = cls.get_or_none(mp, part_number) if obj: return obj return cls.create(mp, part_number)
[ "def", "get_or_create", "(", "cls", ",", "mp", ",", "part_number", ")", ":", "obj", "=", "cls", ".", "get_or_none", "(", "mp", ",", "part_number", ")", "if", "obj", ":", "return", "obj", "return", "cls", ".", "create", "(", "mp", ",", "part_number", ...
Get or create a part.
[ "Get", "or", "create", "a", "part", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1648-L1653
train
41,984
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Part.query_by_multipart
def query_by_multipart(cls, multipart): """Get all parts for a specific multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A :class:`invenio_files_rest.models.Part` instance. """ upload_id = multipart.upload_id \ if isinstance(multipart, MultipartObject) else multipart return cls.query.filter_by( upload_id=upload_id )
python
def query_by_multipart(cls, multipart): """Get all parts for a specific multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A :class:`invenio_files_rest.models.Part` instance. """ upload_id = multipart.upload_id \ if isinstance(multipart, MultipartObject) else multipart return cls.query.filter_by( upload_id=upload_id )
[ "def", "query_by_multipart", "(", "cls", ",", "multipart", ")", ":", "upload_id", "=", "multipart", ".", "upload_id", "if", "isinstance", "(", "multipart", ",", "MultipartObject", ")", "else", "multipart", "return", "cls", ".", "query", ".", "filter_by", "(", ...
Get all parts for a specific multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A :class:`invenio_files_rest.models.Part` instance.
[ "Get", "all", "parts", "for", "a", "specific", "multipart", "upload", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1664-L1675
train
41,985
inveniosoftware/invenio-files-rest
invenio_files_rest/models.py
Part.set_contents
def set_contents(self, stream, progress_callback=None): """Save contents of stream to part of file instance. If a the MultipartObject is completed this methods raises an ``MultipartAlreadyCompleted`` exception. :param stream: File-like stream. :param size: Size of stream if known. :param chunk_size: Desired chunk size to read stream in. It is up to the storage interface if it respects this value. """ size, checksum = self.multipart.file.update_contents( stream, seek=self.start_byte, size=self.part_size, progress_callback=progress_callback, ) self.checksum = checksum return self
python
def set_contents(self, stream, progress_callback=None): """Save contents of stream to part of file instance. If a the MultipartObject is completed this methods raises an ``MultipartAlreadyCompleted`` exception. :param stream: File-like stream. :param size: Size of stream if known. :param chunk_size: Desired chunk size to read stream in. It is up to the storage interface if it respects this value. """ size, checksum = self.multipart.file.update_contents( stream, seek=self.start_byte, size=self.part_size, progress_callback=progress_callback, ) self.checksum = checksum return self
[ "def", "set_contents", "(", "self", ",", "stream", ",", "progress_callback", "=", "None", ")", ":", "size", ",", "checksum", "=", "self", ".", "multipart", ".", "file", ".", "update_contents", "(", "stream", ",", "seek", "=", "self", ".", "start_byte", "...
Save contents of stream to part of file instance. If a the MultipartObject is completed this methods raises an ``MultipartAlreadyCompleted`` exception. :param stream: File-like stream. :param size: Size of stream if known. :param chunk_size: Desired chunk size to read stream in. It is up to the storage interface if it respects this value.
[ "Save", "contents", "of", "stream", "to", "part", "of", "file", "instance", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1683-L1699
train
41,986
django-cumulus/django-cumulus
cumulus/context_processors.py
cdn_url
def cdn_url(request): """ A context processor that exposes the full CDN URL in templates. """ cdn_url, ssl_url = _get_container_urls(CumulusStorage()) static_url = settings.STATIC_URL return { "CDN_URL": cdn_url + static_url, "CDN_SSL_URL": ssl_url + static_url, }
python
def cdn_url(request): """ A context processor that exposes the full CDN URL in templates. """ cdn_url, ssl_url = _get_container_urls(CumulusStorage()) static_url = settings.STATIC_URL return { "CDN_URL": cdn_url + static_url, "CDN_SSL_URL": ssl_url + static_url, }
[ "def", "cdn_url", "(", "request", ")", ":", "cdn_url", ",", "ssl_url", "=", "_get_container_urls", "(", "CumulusStorage", "(", ")", ")", "static_url", "=", "settings", ".", "STATIC_URL", "return", "{", "\"CDN_URL\"", ":", "cdn_url", "+", "static_url", ",", "...
A context processor that exposes the full CDN URL in templates.
[ "A", "context", "processor", "that", "exposes", "the", "full", "CDN", "URL", "in", "templates", "." ]
64feb07b857af28f226be4899e875c29405e261d
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/context_processors.py#L19-L29
train
41,987
django-cumulus/django-cumulus
cumulus/context_processors.py
static_cdn_url
def static_cdn_url(request): """ A context processor that exposes the full static CDN URL as static URL in templates. """ cdn_url, ssl_url = _get_container_urls(CumulusStaticStorage()) static_url = settings.STATIC_URL return { "STATIC_URL": cdn_url + static_url, "STATIC_SSL_URL": ssl_url + static_url, "LOCAL_STATIC_URL": static_url, }
python
def static_cdn_url(request): """ A context processor that exposes the full static CDN URL as static URL in templates. """ cdn_url, ssl_url = _get_container_urls(CumulusStaticStorage()) static_url = settings.STATIC_URL return { "STATIC_URL": cdn_url + static_url, "STATIC_SSL_URL": ssl_url + static_url, "LOCAL_STATIC_URL": static_url, }
[ "def", "static_cdn_url", "(", "request", ")", ":", "cdn_url", ",", "ssl_url", "=", "_get_container_urls", "(", "CumulusStaticStorage", "(", ")", ")", "static_url", "=", "settings", ".", "STATIC_URL", "return", "{", "\"STATIC_URL\"", ":", "cdn_url", "+", "static_...
A context processor that exposes the full static CDN URL as static URL in templates.
[ "A", "context", "processor", "that", "exposes", "the", "full", "static", "CDN", "URL", "as", "static", "URL", "in", "templates", "." ]
64feb07b857af28f226be4899e875c29405e261d
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/context_processors.py#L32-L44
train
41,988
swistakm/python-gmaps
src/gmaps/geocoding.py
Geocoding.reverse
def reverse(self, lat, lon, result_type=None, location_type=None, language=None, sensor=None): """Reverse geocode with given latitude and longitude. :param lat: latitude of queried point :param lon: longitude of queried point :param result_type: list of result_type for filtered search. Accepted values: https://developers.google.com/maps/documentation/geocoding/intro#Types **Important**: this feature may require using API key to work. :param location_type: list of location_type for filtered search. :param language: the language in which to return results. For full list of laguages go to Google Maps API docs :param sensor: override default client sensor parameter .. note:: Google API allows to specify both latlng and address params but it makes no sense and would not reverse geocode your query, so here geocoding and reverse geocoding are separated """ parameters = dict( latlng="%f,%f" % (lat, lon), result_type=result_type, location_type=location_type, language=language, sensor=sensor, ) return self._make_request(self.GEOCODE_URL, parameters, "results")
python
def reverse(self, lat, lon, result_type=None, location_type=None, language=None, sensor=None): """Reverse geocode with given latitude and longitude. :param lat: latitude of queried point :param lon: longitude of queried point :param result_type: list of result_type for filtered search. Accepted values: https://developers.google.com/maps/documentation/geocoding/intro#Types **Important**: this feature may require using API key to work. :param location_type: list of location_type for filtered search. :param language: the language in which to return results. For full list of laguages go to Google Maps API docs :param sensor: override default client sensor parameter .. note:: Google API allows to specify both latlng and address params but it makes no sense and would not reverse geocode your query, so here geocoding and reverse geocoding are separated """ parameters = dict( latlng="%f,%f" % (lat, lon), result_type=result_type, location_type=location_type, language=language, sensor=sensor, ) return self._make_request(self.GEOCODE_URL, parameters, "results")
[ "def", "reverse", "(", "self", ",", "lat", ",", "lon", ",", "result_type", "=", "None", ",", "location_type", "=", "None", ",", "language", "=", "None", ",", "sensor", "=", "None", ")", ":", "parameters", "=", "dict", "(", "latlng", "=", "\"%f,%f\"", ...
Reverse geocode with given latitude and longitude. :param lat: latitude of queried point :param lon: longitude of queried point :param result_type: list of result_type for filtered search. Accepted values: https://developers.google.com/maps/documentation/geocoding/intro#Types **Important**: this feature may require using API key to work. :param location_type: list of location_type for filtered search. :param language: the language in which to return results. For full list of laguages go to Google Maps API docs :param sensor: override default client sensor parameter .. note:: Google API allows to specify both latlng and address params but it makes no sense and would not reverse geocode your query, so here geocoding and reverse geocoding are separated
[ "Reverse", "geocode", "with", "given", "latitude", "and", "longitude", "." ]
ef3bdea6f02277200f21a09f99d4e2aebad762b9
https://github.com/swistakm/python-gmaps/blob/ef3bdea6f02277200f21a09f99d4e2aebad762b9/src/gmaps/geocoding.py#L39-L65
train
41,989
inveniosoftware/invenio-files-rest
invenio_files_rest/storage/base.py
check_sizelimit
def check_sizelimit(size_limit, bytes_written, total_size): """Check if size limit was exceeded. :param size_limit: The size limit. :param bytes_written: The total number of bytes written. :param total_size: The total file size. :raises invenio_files_rest.errors.UnexpectedFileSizeError: If the bytes written exceed the total size. :raises invenio_files_rest.errors.FileSizeError: If the bytes written are major than the limit size. """ if size_limit is not None and bytes_written > size_limit: desc = 'File size limit exceeded.' \ if isinstance(size_limit, int) else size_limit.reason raise FileSizeError(description=desc) # Never write more than advertised if total_size is not None and bytes_written > total_size: raise UnexpectedFileSizeError( description='File is bigger than expected.')
python
def check_sizelimit(size_limit, bytes_written, total_size): """Check if size limit was exceeded. :param size_limit: The size limit. :param bytes_written: The total number of bytes written. :param total_size: The total file size. :raises invenio_files_rest.errors.UnexpectedFileSizeError: If the bytes written exceed the total size. :raises invenio_files_rest.errors.FileSizeError: If the bytes written are major than the limit size. """ if size_limit is not None and bytes_written > size_limit: desc = 'File size limit exceeded.' \ if isinstance(size_limit, int) else size_limit.reason raise FileSizeError(description=desc) # Never write more than advertised if total_size is not None and bytes_written > total_size: raise UnexpectedFileSizeError( description='File is bigger than expected.')
[ "def", "check_sizelimit", "(", "size_limit", ",", "bytes_written", ",", "total_size", ")", ":", "if", "size_limit", "is", "not", "None", "and", "bytes_written", ">", "size_limit", ":", "desc", "=", "'File size limit exceeded.'", "if", "isinstance", "(", "size_limi...
Check if size limit was exceeded. :param size_limit: The size limit. :param bytes_written: The total number of bytes written. :param total_size: The total file size. :raises invenio_files_rest.errors.UnexpectedFileSizeError: If the bytes written exceed the total size. :raises invenio_files_rest.errors.FileSizeError: If the bytes written are major than the limit size.
[ "Check", "if", "size", "limit", "was", "exceeded", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/base.py#L21-L40
train
41,990
inveniosoftware/invenio-files-rest
invenio_files_rest/storage/base.py
FileStorage.send_file
def send_file(self, filename, mimetype=None, restricted=True, checksum=None, trusted=False, chunk_size=None, as_attachment=False): """Send the file to the client.""" try: fp = self.open(mode='rb') except Exception as e: raise StorageError('Could not send file: {}'.format(e)) try: md5_checksum = None if checksum: algo, value = checksum.split(':') if algo == 'md5': md5_checksum = value # Send stream is responsible for closing the file. return send_stream( fp, filename, self._size, self._modified, mimetype=mimetype, restricted=restricted, etag=checksum, content_md5=md5_checksum, chunk_size=chunk_size, trusted=trusted, as_attachment=as_attachment, ) except Exception as e: fp.close() raise StorageError('Could not send file: {}'.format(e))
python
def send_file(self, filename, mimetype=None, restricted=True, checksum=None, trusted=False, chunk_size=None, as_attachment=False): """Send the file to the client.""" try: fp = self.open(mode='rb') except Exception as e: raise StorageError('Could not send file: {}'.format(e)) try: md5_checksum = None if checksum: algo, value = checksum.split(':') if algo == 'md5': md5_checksum = value # Send stream is responsible for closing the file. return send_stream( fp, filename, self._size, self._modified, mimetype=mimetype, restricted=restricted, etag=checksum, content_md5=md5_checksum, chunk_size=chunk_size, trusted=trusted, as_attachment=as_attachment, ) except Exception as e: fp.close() raise StorageError('Could not send file: {}'.format(e))
[ "def", "send_file", "(", "self", ",", "filename", ",", "mimetype", "=", "None", ",", "restricted", "=", "True", ",", "checksum", "=", "None", ",", "trusted", "=", "False", ",", "chunk_size", "=", "None", ",", "as_attachment", "=", "False", ")", ":", "t...
Send the file to the client.
[ "Send", "the", "file", "to", "the", "client", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/base.py#L92-L124
train
41,991
inveniosoftware/invenio-files-rest
invenio_files_rest/storage/base.py
FileStorage.checksum
def checksum(self, chunk_size=None, progress_callback=None, **kwargs): """Compute checksum of file.""" fp = self.open(mode='rb') try: value = self._compute_checksum( fp, size=self._size, chunk_size=None, progress_callback=progress_callback) except StorageError: raise finally: fp.close() return value
python
def checksum(self, chunk_size=None, progress_callback=None, **kwargs): """Compute checksum of file.""" fp = self.open(mode='rb') try: value = self._compute_checksum( fp, size=self._size, chunk_size=None, progress_callback=progress_callback) except StorageError: raise finally: fp.close() return value
[ "def", "checksum", "(", "self", ",", "chunk_size", "=", "None", ",", "progress_callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fp", "=", "self", ".", "open", "(", "mode", "=", "'rb'", ")", "try", ":", "value", "=", "self", ".", "_comput...
Compute checksum of file.
[ "Compute", "checksum", "of", "file", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/base.py#L126-L137
train
41,992
inveniosoftware/invenio-files-rest
invenio_files_rest/storage/base.py
FileStorage.copy
def copy(self, src, chunk_size=None, progress_callback=None): """Copy data from another file instance. :param src: Source stream. :param chunk_size: Chunk size to read from source stream. """ fp = src.open(mode='rb') try: return self.save( fp, chunk_size=chunk_size, progress_callback=progress_callback) finally: fp.close()
python
def copy(self, src, chunk_size=None, progress_callback=None): """Copy data from another file instance. :param src: Source stream. :param chunk_size: Chunk size to read from source stream. """ fp = src.open(mode='rb') try: return self.save( fp, chunk_size=chunk_size, progress_callback=progress_callback) finally: fp.close()
[ "def", "copy", "(", "self", ",", "src", ",", "chunk_size", "=", "None", ",", "progress_callback", "=", "None", ")", ":", "fp", "=", "src", ".", "open", "(", "mode", "=", "'rb'", ")", "try", ":", "return", "self", ".", "save", "(", "fp", ",", "chu...
Copy data from another file instance. :param src: Source stream. :param chunk_size: Chunk size to read from source stream.
[ "Copy", "data", "from", "another", "file", "instance", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/base.py#L139-L150
train
41,993
inveniosoftware/invenio-files-rest
invenio_files_rest/storage/base.py
FileStorage._write_stream
def _write_stream(self, src, dst, size=None, size_limit=None, chunk_size=None, progress_callback=None): """Get helper to save stream from src to dest + compute checksum. :param src: Source stream. :param dst: Destination stream. :param size: If provided, this exact amount of bytes will be written to the destination file. :param size_limit: ``FileSizeLimit`` instance to limit number of bytes to write. """ chunk_size = chunk_size_or_default(chunk_size) algo, m = self._init_hash() bytes_written = 0 while 1: # Check that size limits aren't bypassed check_sizelimit(size_limit, bytes_written, size) chunk = src.read(chunk_size) if not chunk: if progress_callback: progress_callback(bytes_written, bytes_written) break dst.write(chunk) bytes_written += len(chunk) if m: m.update(chunk) if progress_callback: progress_callback(None, bytes_written) check_size(bytes_written, size) return bytes_written, '{0}:{1}'.format( algo, m.hexdigest()) if m else None
python
def _write_stream(self, src, dst, size=None, size_limit=None, chunk_size=None, progress_callback=None): """Get helper to save stream from src to dest + compute checksum. :param src: Source stream. :param dst: Destination stream. :param size: If provided, this exact amount of bytes will be written to the destination file. :param size_limit: ``FileSizeLimit`` instance to limit number of bytes to write. """ chunk_size = chunk_size_or_default(chunk_size) algo, m = self._init_hash() bytes_written = 0 while 1: # Check that size limits aren't bypassed check_sizelimit(size_limit, bytes_written, size) chunk = src.read(chunk_size) if not chunk: if progress_callback: progress_callback(bytes_written, bytes_written) break dst.write(chunk) bytes_written += len(chunk) if m: m.update(chunk) if progress_callback: progress_callback(None, bytes_written) check_size(bytes_written, size) return bytes_written, '{0}:{1}'.format( algo, m.hexdigest()) if m else None
[ "def", "_write_stream", "(", "self", ",", "src", ",", "dst", ",", "size", "=", "None", ",", "size_limit", "=", "None", ",", "chunk_size", "=", "None", ",", "progress_callback", "=", "None", ")", ":", "chunk_size", "=", "chunk_size_or_default", "(", "chunk_...
Get helper to save stream from src to dest + compute checksum. :param src: Source stream. :param dst: Destination stream. :param size: If provided, this exact amount of bytes will be written to the destination file. :param size_limit: ``FileSizeLimit`` instance to limit number of bytes to write.
[ "Get", "helper", "to", "save", "stream", "from", "src", "to", "dest", "+", "compute", "checksum", "." ]
59a950da61cc8d5882a03c6fde6db2e2ed10befd
https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/base.py#L187-L227
train
41,994
swistakm/python-gmaps
src/gmaps/timezone.py
unixtimestamp
def unixtimestamp(datetime): """Get unix time stamp from that given datetime. If datetime is not tzaware then it's assumed that it is UTC """ epoch = UTC.localize(datetime.utcfromtimestamp(0)) if not datetime.tzinfo: dt = UTC.localize(datetime) else: dt = UTC.normalize(datetime) delta = dt - epoch return total_seconds(delta)
python
def unixtimestamp(datetime): """Get unix time stamp from that given datetime. If datetime is not tzaware then it's assumed that it is UTC """ epoch = UTC.localize(datetime.utcfromtimestamp(0)) if not datetime.tzinfo: dt = UTC.localize(datetime) else: dt = UTC.normalize(datetime) delta = dt - epoch return total_seconds(delta)
[ "def", "unixtimestamp", "(", "datetime", ")", ":", "epoch", "=", "UTC", ".", "localize", "(", "datetime", ".", "utcfromtimestamp", "(", "0", ")", ")", "if", "not", "datetime", ".", "tzinfo", ":", "dt", "=", "UTC", ".", "localize", "(", "datetime", ")",...
Get unix time stamp from that given datetime. If datetime is not tzaware then it's assumed that it is UTC
[ "Get", "unix", "time", "stamp", "from", "that", "given", "datetime", ".", "If", "datetime", "is", "not", "tzaware", "then", "it", "s", "assumed", "that", "it", "is", "UTC" ]
ef3bdea6f02277200f21a09f99d4e2aebad762b9
https://github.com/swistakm/python-gmaps/blob/ef3bdea6f02277200f21a09f99d4e2aebad762b9/src/gmaps/timezone.py#L14-L24
train
41,995
swistakm/python-gmaps
src/gmaps/timezone.py
Timezone.timezone
def timezone(self, lat, lon, datetime, language=None, sensor=None): """Get time offset data for given location. :param lat: Latitude of queried point :param lon: Longitude of queried point :param language: The language in which to return results. For full list of laguages go to Google Maps API docs :param datetime: Desired time. The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied. datetime should be timezone aware. If it isn't the UTC timezone is assumed. :type datetime: datetime.datetime :param sensor: Override default client sensor parameter """ parameters = dict( location="%f,%f" % (lat, lon), timestamp=unixtimestamp(datetime), language=language, sensor=sensor, ) return self._make_request(self.TIMEZONE_URL, parameters, None)
python
def timezone(self, lat, lon, datetime, language=None, sensor=None): """Get time offset data for given location. :param lat: Latitude of queried point :param lon: Longitude of queried point :param language: The language in which to return results. For full list of laguages go to Google Maps API docs :param datetime: Desired time. The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied. datetime should be timezone aware. If it isn't the UTC timezone is assumed. :type datetime: datetime.datetime :param sensor: Override default client sensor parameter """ parameters = dict( location="%f,%f" % (lat, lon), timestamp=unixtimestamp(datetime), language=language, sensor=sensor, ) return self._make_request(self.TIMEZONE_URL, parameters, None)
[ "def", "timezone", "(", "self", ",", "lat", ",", "lon", ",", "datetime", ",", "language", "=", "None", ",", "sensor", "=", "None", ")", ":", "parameters", "=", "dict", "(", "location", "=", "\"%f,%f\"", "%", "(", "lat", ",", "lon", ")", ",", "times...
Get time offset data for given location. :param lat: Latitude of queried point :param lon: Longitude of queried point :param language: The language in which to return results. For full list of laguages go to Google Maps API docs :param datetime: Desired time. The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied. datetime should be timezone aware. If it isn't the UTC timezone is assumed. :type datetime: datetime.datetime :param sensor: Override default client sensor parameter
[ "Get", "time", "offset", "data", "for", "given", "location", "." ]
ef3bdea6f02277200f21a09f99d4e2aebad762b9
https://github.com/swistakm/python-gmaps/blob/ef3bdea6f02277200f21a09f99d4e2aebad762b9/src/gmaps/timezone.py#L30-L52
train
41,996
inveniosoftware/invenio-records-files
invenio_records_files/api.py
_writable
def _writable(method): """Check that record is in defined status. :param method: Method to be decorated. :returns: Function decorated. """ @wraps(method) def wrapper(self, *args, **kwargs): """Send record for indexing. :returns: Execution result of the decorated method. :raises InvalidOperationError: It occurs when the bucket is locked or deleted. """ if self.bucket.locked or self.bucket.deleted: raise InvalidOperationError() return method(self, *args, **kwargs) return wrapper
python
def _writable(method): """Check that record is in defined status. :param method: Method to be decorated. :returns: Function decorated. """ @wraps(method) def wrapper(self, *args, **kwargs): """Send record for indexing. :returns: Execution result of the decorated method. :raises InvalidOperationError: It occurs when the bucket is locked or deleted. """ if self.bucket.locked or self.bucket.deleted: raise InvalidOperationError() return method(self, *args, **kwargs) return wrapper
[ "def", "_writable", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Send record for indexing.\n\n :returns: Execution result of the decorated method.\n\n ...
Check that record is in defined status. :param method: Method to be decorated. :returns: Function decorated.
[ "Check", "that", "record", "is", "in", "defined", "status", "." ]
c410eba986ea43be7e97082d5dcbbdc19ccec39c
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L80-L98
train
41,997
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FileObject.get_version
def get_version(self, version_id=None): """Return specific version ``ObjectVersion`` instance or HEAD. :param version_id: Version ID of the object. :returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or HEAD of the stored object. """ return ObjectVersion.get(bucket=self.obj.bucket, key=self.obj.key, version_id=version_id)
python
def get_version(self, version_id=None): """Return specific version ``ObjectVersion`` instance or HEAD. :param version_id: Version ID of the object. :returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or HEAD of the stored object. """ return ObjectVersion.get(bucket=self.obj.bucket, key=self.obj.key, version_id=version_id)
[ "def", "get_version", "(", "self", ",", "version_id", "=", "None", ")", ":", "return", "ObjectVersion", ".", "get", "(", "bucket", "=", "self", ".", "obj", ".", "bucket", ",", "key", "=", "self", ".", "obj", ".", "key", ",", "version_id", "=", "versi...
Return specific version ``ObjectVersion`` instance or HEAD. :param version_id: Version ID of the object. :returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or HEAD of the stored object.
[ "Return", "specific", "version", "ObjectVersion", "instance", "or", "HEAD", "." ]
c410eba986ea43be7e97082d5dcbbdc19ccec39c
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L32-L40
train
41,998
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FileObject.get
def get(self, key, default=None): """Proxy to ``obj``. :param key: Metadata key which holds the value. :returns: Metadata value of the specified key or default. """ if hasattr(self.obj, key): return getattr(self.obj, key) return self.data.get(key, default)
python
def get(self, key, default=None): """Proxy to ``obj``. :param key: Metadata key which holds the value. :returns: Metadata value of the specified key or default. """ if hasattr(self.obj, key): return getattr(self.obj, key) return self.data.get(key, default)
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "hasattr", "(", "self", ".", "obj", ",", "key", ")", ":", "return", "getattr", "(", "self", ".", "obj", ",", "key", ")", "return", "self", ".", "data", ".", "ge...
Proxy to ``obj``. :param key: Metadata key which holds the value. :returns: Metadata value of the specified key or default.
[ "Proxy", "to", "obj", "." ]
c410eba986ea43be7e97082d5dcbbdc19ccec39c
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L42-L50
train
41,999