index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
18,446
miarec_s3fs.s3fs
_info_from_object
Make an info dict from an s3 Object.
def _info_from_object(self, obj, namespaces): """Make an info dict from an s3 Object.""" key = obj.key path = self._key_to_path(key) name = basename(path.rstrip("/")) is_dir = key.endswith(self.delimiter) info = {"basic": {"name": name, "is_dir": is_dir}} if "details" in namespaces: _type = int(ResourceType.directory if is_dir else ResourceType.file) info["details"] = { "accessed": None, "modified": datetime_to_epoch(obj.last_modified), "size": obj.content_length, "type": _type, } if "s3" in namespaces: s3info = info["s3"] = {} for name in self._object_attributes: value = getattr(obj, name, None) if isinstance(value, datetime): value = datetime_to_epoch(value) s3info[name] = value if "urls" in namespaces: url = self.client.generate_presigned_url( ClientMethod="get_object", Params={"Bucket": self._bucket_name, "Key": key}, ) info["urls"] = {"download": url} return info
(self, obj, namespaces)
18,447
miarec_s3fs.s3fs
_key_to_path
null
def _key_to_path(self, key): return key.replace(self.delimiter, "/")
(self, key)
18,448
miarec_s3fs.s3fs
_path_to_dir_key
Converts an fs path to a s3 key.
def _path_to_dir_key(self, path): """Converts an fs path to a s3 key.""" _path = relpath(normpath(path)) _key = ( forcedir("{}/{}".format(self._prefix, _path)) .lstrip("/") .replace("/", self.delimiter) ) return _key
(self, path)
18,449
miarec_s3fs.s3fs
_path_to_key
Converts an fs path to a s3 key.
def _path_to_key(self, path): """Converts an fs path to a s3 key.""" _path = relpath(normpath(path)) _key = ( "{}/{}".format(self._prefix, _path).lstrip("/").replace("/", self.delimiter) ) return _key
(self, path)
18,450
fs.base
appendbytes
Append bytes to the end of a file, creating it if needed. Arguments: path (str): Path to a file. data (bytes): Bytes to append. Raises: TypeError: If ``data`` is not a `bytes` instance. fs.errors.ResourceNotFound: If a parent directory of ``path`` does not exist.
def appendbytes(self, path, data): # type: (Text, bytes) -> None # FIXME(@althonos): accept bytearray and memoryview as well ? """Append bytes to the end of a file, creating it if needed. Arguments: path (str): Path to a file. data (bytes): Bytes to append. Raises: TypeError: If ``data`` is not a `bytes` instance. fs.errors.ResourceNotFound: If a parent directory of ``path`` does not exist. """ if not isinstance(data, bytes): raise TypeError("must be bytes") with self._lock: with self.open(path, "ab") as append_file: append_file.write(data)
(self, path, data)
18,451
fs.base
appendtext
Append text to the end of a file, creating it if needed. Arguments: path (str): Path to a file. text (str): Text to append. encoding (str): Encoding for text files (defaults to ``utf-8``). errors (str, optional): What to do with unicode decode errors (see `codecs` module for more information). newline (str): Newline parameter. Raises: TypeError: if ``text`` is not an unicode string. fs.errors.ResourceNotFound: if a parent directory of ``path`` does not exist.
def appendtext( self, path, # type: Text text, # type: Text encoding="utf-8", # type: Text errors=None, # type: Optional[Text] newline="", # type: Text ): # type: (...) -> None """Append text to the end of a file, creating it if needed. Arguments: path (str): Path to a file. text (str): Text to append. encoding (str): Encoding for text files (defaults to ``utf-8``). errors (str, optional): What to do with unicode decode errors (see `codecs` module for more information). newline (str): Newline parameter. Raises: TypeError: if ``text`` is not an unicode string. fs.errors.ResourceNotFound: if a parent directory of ``path`` does not exist. """ if not isinstance(text, six.text_type): raise TypeError("must be unicode string") with self._lock: with self.open( path, "at", encoding=encoding, errors=errors, newline=newline ) as append_file: append_file.write(text)
(self, path, text, encoding='utf-8', errors=None, newline='')
18,452
fs.base
check
Check if a filesystem may be used. Raises: fs.errors.FilesystemClosed: if the filesystem is closed.
def check(self): # type: () -> None """Check if a filesystem may be used. Raises: fs.errors.FilesystemClosed: if the filesystem is closed. """ if self.isclosed(): raise errors.FilesystemClosed()
(self)
18,453
fs.base
close
Close the filesystem and release any resources. It is important to call this method when you have finished working with the filesystem. Some filesystems may not finalize changes until they are closed (archives for example). You may call this method explicitly (it is safe to call close multiple times), or you can use the filesystem as a context manager to automatically close. Example: >>> with OSFS('~/Desktop') as desktop_fs: ... desktop_fs.writetext( ... 'note.txt', ... "Don't forget to tape Game of Thrones" ... ) If you attempt to use a filesystem that has been closed, a `~fs.errors.FilesystemClosed` exception will be thrown.
def close(self): # type: () -> None """Close the filesystem and release any resources. It is important to call this method when you have finished working with the filesystem. Some filesystems may not finalize changes until they are closed (archives for example). You may call this method explicitly (it is safe to call close multiple times), or you can use the filesystem as a context manager to automatically close. Example: >>> with OSFS('~/Desktop') as desktop_fs: ... desktop_fs.writetext( ... 'note.txt', ... "Don't forget to tape Game of Thrones" ... ) If you attempt to use a filesystem that has been closed, a `~fs.errors.FilesystemClosed` exception will be thrown. """ self._closed = True
(self)
18,454
miarec_s3fs.s3fs
copy
null
def copy(self, src_path, dst_path, overwrite=False, preserve_time=False): if not overwrite and self.exists(dst_path): raise errors.DestinationExists(dst_path) _src_path = self.validatepath(src_path) _dst_path = self.validatepath(dst_path) if self.strict: if not self.isdir(dirname(_dst_path)): raise errors.ResourceNotFound(dst_path) _src_key = self._path_to_key(_src_path) _dst_key = self._path_to_key(_dst_path) try: with s3errors(src_path): self.client.copy_object( Bucket=self._bucket_name, Key=_dst_key, CopySource={"Bucket": self._bucket_name, "Key": _src_key}, **self._get_upload_args(_src_key) ) except errors.ResourceNotFound: if self.exists(src_path): raise errors.FileExpected(src_path) raise
(self, src_path, dst_path, overwrite=False, preserve_time=False)
18,455
fs.base
copydir
Copy the contents of ``src_path`` to ``dst_path``. Arguments: src_path (str): Path of source directory. dst_path (str): Path to destination directory. create (bool): If `True`, then ``dst_path`` will be created if it doesn't exist already (defaults to `False`). preserve_time (bool): If `True`, try to preserve mtime of the resource (defaults to `False`). Raises: fs.errors.ResourceNotFound: If the ``dst_path`` does not exist, and ``create`` is not `True`. fs.errors.DirectoryExpected: If ``src_path`` is not a directory.
def copydir( self, src_path, # type: Text dst_path, # type: Text create=False, # type: bool preserve_time=False, # type: bool ): # type: (...) -> None """Copy the contents of ``src_path`` to ``dst_path``. Arguments: src_path (str): Path of source directory. dst_path (str): Path to destination directory. create (bool): If `True`, then ``dst_path`` will be created if it doesn't exist already (defaults to `False`). preserve_time (bool): If `True`, try to preserve mtime of the resource (defaults to `False`). Raises: fs.errors.ResourceNotFound: If the ``dst_path`` does not exist, and ``create`` is not `True`. fs.errors.DirectoryExpected: If ``src_path`` is not a directory. """ with self._lock: if not create and not self.exists(dst_path): raise errors.ResourceNotFound(dst_path) if not self.getinfo(src_path).is_dir: raise errors.DirectoryExpected(src_path) copy.copy_dir(self, src_path, self, dst_path, preserve_time=preserve_time)
(self, src_path, dst_path, create=False, preserve_time=False)
18,456
fs.base
create
Create an empty file. The default behavior is to create a new file if one doesn't already exist. If ``wipe`` is `True`, any existing file will be truncated. Arguments: path (str): Path to a new file in the filesystem. wipe (bool): If `True`, truncate any existing file to 0 bytes (defaults to `False`). Returns: bool: `True` if a new file had to be created.
def create(self, path, wipe=False): # type: (Text, bool) -> bool """Create an empty file. The default behavior is to create a new file if one doesn't already exist. If ``wipe`` is `True`, any existing file will be truncated. Arguments: path (str): Path to a new file in the filesystem. wipe (bool): If `True`, truncate any existing file to 0 bytes (defaults to `False`). Returns: bool: `True` if a new file had to be created. """ with self._lock: if not wipe and self.exists(path): return False with closing(self.open(path, "wb")): pass return True
(self, path, wipe=False)
18,457
fs.base
desc
Return a short descriptive text regarding a path. Arguments: path (str): A path to a resource on the filesystem. Returns: str: a short description of the path. Raises: fs.errors.ResourceNotFound: If ``path`` does not exist.
def desc(self, path): # type: (Text) -> Text """Return a short descriptive text regarding a path. Arguments: path (str): A path to a resource on the filesystem. Returns: str: a short description of the path. Raises: fs.errors.ResourceNotFound: If ``path`` does not exist. """ if not self.exists(path): raise errors.ResourceNotFound(path) try: syspath = self.getsyspath(path) except (errors.ResourceNotFound, errors.NoSysPath): return "{} on {}".format(path, self) else: return syspath
(self, path)
18,458
miarec_s3fs.s3fs
download
null
def download(self, path, file, chunk_size=None, **options): self.check() if self.strict: info = self.getinfo(path) if not info.is_file: raise errors.FileExpected(path) _path = self.validatepath(path) _key = self._path_to_key(_path) with s3errors(path): self.client.download_fileobj( self._bucket_name, _key, file, ExtraArgs=self.download_args )
(self, path, file, chunk_size=None, **options)
18,459
miarec_s3fs.s3fs
exists
null
def exists(self, path): self.check() _path = self.validatepath(path) if _path == "/": return True _key = self._path_to_dir_key(_path) try: self._get_object(path, _key) except errors.ResourceNotFound: return False else: return True
(self, path)
18,460
fs.base
filterdir
Get an iterator of resource info, filtered by patterns. This method enhances `~fs.base.FS.scandir` with additional filtering functionality. Arguments: path (str): A path to a directory on the filesystem. files (list, optional): A list of UNIX shell-style patterns to filter file names, e.g. ``['*.py']``. dirs (list, optional): A list of UNIX shell-style patterns to filter directory names. exclude_dirs (list, optional): A list of patterns used to exclude directories. exclude_files (list, optional): A list of patterns used to exclude files. namespaces (list, optional): A list of namespaces to include in the resource information, e.g. ``['basic', 'access']``. page (tuple, optional): May be a tuple of ``(<start>, <end>)`` indexes to return an iterator of a subset of the resource info, or `None` to iterate over the entire directory. Paging a directory scan may be necessary for very large directories. Returns: ~collections.abc.Iterator: an iterator of `Info` objects.
def filterdir( self, path, # type: Text files=None, # type: Optional[Iterable[Text]] dirs=None, # type: Optional[Iterable[Text]] exclude_dirs=None, # type: Optional[Iterable[Text]] exclude_files=None, # type: Optional[Iterable[Text]] namespaces=None, # type: Optional[Collection[Text]] page=None, # type: Optional[Tuple[int, int]] ): # type: (...) -> Iterator[Info] """Get an iterator of resource info, filtered by patterns. This method enhances `~fs.base.FS.scandir` with additional filtering functionality. Arguments: path (str): A path to a directory on the filesystem. files (list, optional): A list of UNIX shell-style patterns to filter file names, e.g. ``['*.py']``. dirs (list, optional): A list of UNIX shell-style patterns to filter directory names. exclude_dirs (list, optional): A list of patterns used to exclude directories. exclude_files (list, optional): A list of patterns used to exclude files. namespaces (list, optional): A list of namespaces to include in the resource information, e.g. ``['basic', 'access']``. page (tuple, optional): May be a tuple of ``(<start>, <end>)`` indexes to return an iterator of a subset of the resource info, or `None` to iterate over the entire directory. Paging a directory scan may be necessary for very large directories. Returns: ~collections.abc.Iterator: an iterator of `Info` objects. """ resources = self.scandir(path, namespaces=namespaces) filters = [] def match_dir(patterns, info): # type: (Optional[Iterable[Text]], Info) -> bool """Pattern match info.name.""" return info.is_file or self.match(patterns, info.name) def match_file(patterns, info): # type: (Optional[Iterable[Text]], Info) -> bool """Pattern match info.name.""" return info.is_dir or self.match(patterns, info.name) def exclude_dir(patterns, info): # type: (Optional[Iterable[Text]], Info) -> bool """Pattern match info.name.""" return info.is_file or not self.match(patterns, info.name) def exclude_file(patterns, info): # type: (Optional[Iterable[Text]], Info) -> bool """Pattern match info.name.""" return info.is_dir or not self.match(patterns, info.name) if files: filters.append(partial(match_file, files)) if dirs: filters.append(partial(match_dir, dirs)) if exclude_dirs: filters.append(partial(exclude_dir, exclude_dirs)) if exclude_files: filters.append(partial(exclude_file, exclude_files)) if filters: resources = ( info for info in resources if all(_filter(info) for _filter in filters) ) iter_info = iter(resources) if page is not None: start, end = page iter_info = itertools.islice(iter_info, start, end) return iter_info
(self, path, files=None, dirs=None, exclude_dirs=None, exclude_files=None, namespaces=None, page=None)
18,461
fs.base
getbasic
Get the *basic* resource info. This method is shorthand for the following:: fs.getinfo(path, namespaces=['basic']) Arguments: path (str): A path on the filesystem. Returns: ~fs.info.Info: Resource information object for ``path``. Note: .. deprecated:: 2.4.13 Please use `~FS.getinfo` directly, which is required to always return the *basic* namespace.
def getbasic(self, path): # type: (Text) -> Info """Get the *basic* resource info. This method is shorthand for the following:: fs.getinfo(path, namespaces=['basic']) Arguments: path (str): A path on the filesystem. Returns: ~fs.info.Info: Resource information object for ``path``. Note: .. deprecated:: 2.4.13 Please use `~FS.getinfo` directly, which is required to always return the *basic* namespace. """ warnings.warn( "method 'getbasic' has been deprecated, please use 'getinfo'", DeprecationWarning, ) return self.getinfo(path, namespaces=["basic"])
(self, path)
18,462
fs.base
readbytes
Get the contents of a file as bytes. Arguments: path (str): A path to a readable file on the filesystem. Returns: bytes: the file contents. Raises: fs.errors.FileExpected: if ``path`` exists but is not a file. fs.errors.ResourceNotFound: if ``path`` does not exist. Note: .. deprecated:: 2.2.0 Please use `~readbytes`
def _new_name(method, old_name): """Return a method with a deprecation warning.""" # Looks suspiciously like a decorator, but isn't! @wraps(method) def _method(*args, **kwargs): warnings.warn( "method '{}' has been deprecated, please rename to '{}'".format( old_name, method.__name__ ), DeprecationWarning, ) return method(*args, **kwargs) deprecated_msg = """ Note: .. deprecated:: 2.2.0 Please use `~{}` """.format( method.__name__ ) if getattr(_method, "__doc__", None) is not None: _method.__doc__ += deprecated_msg return _method
(self, path)
18,463
fs.base
getdetails
Get the *details* resource info. This method is shorthand for the following:: fs.getinfo(path, namespaces=['details']) Arguments: path (str): A path on the filesystem. Returns: ~fs.info.Info: Resource information object for ``path``.
def getdetails(self, path): # type: (Text) -> Info """Get the *details* resource info. This method is shorthand for the following:: fs.getinfo(path, namespaces=['details']) Arguments: path (str): A path on the filesystem. Returns: ~fs.info.Info: Resource information object for ``path``. """ return self.getinfo(path, namespaces=["details"])
(self, path)
18,464
fs.base
download
Copy a file from the filesystem to a file-like object. This may be more efficient that opening and copying files manually if the filesystem supplies an optimized method. Note that the file object ``file`` will *not* be closed by this method. Take care to close it after this method completes (ideally with a context manager). Arguments: path (str): Path to a resource. file (file-like): A file-like object open for writing in binary mode. chunk_size (int, optional): Number of bytes to read at a time, if a simple copy is used, or `None` to use sensible default. **options: Implementation specific options required to open the source file. Example: >>> with open('starwars.mov', 'wb') as write_file: ... my_fs.download('/Videos/starwars.mov', write_file) Raises: fs.errors.ResourceNotFound: if ``path`` does not exist. Note: .. deprecated:: 2.2.0 Please use `~download`
def _new_name(method, old_name): """Return a method with a deprecation warning.""" # Looks suspiciously like a decorator, but isn't! @wraps(method) def _method(*args, **kwargs): warnings.warn( "method '{}' has been deprecated, please rename to '{}'".format( old_name, method.__name__ ), DeprecationWarning, ) return method(*args, **kwargs) deprecated_msg = """ Note: .. deprecated:: 2.2.0 Please use `~{}` """.format( method.__name__ ) if getattr(_method, "__doc__", None) is not None: _method.__doc__ += deprecated_msg return _method
(self, path, file, chunk_size=None, **options)
18,465
miarec_s3fs.s3fs
getinfo
null
def getinfo(self, path, namespaces=None): self.check() namespaces = namespaces or () _path = self.validatepath(path) _key = self._path_to_key(_path) try: dir_path = dirname(_path) if dir_path != "/": _dir_key = self._path_to_dir_key(dir_path) with s3errors(path): obj = self.s3.Object(self._bucket_name, _dir_key) obj.load() except errors.ResourceNotFound: raise errors.ResourceNotFound(path) if _path == "/": return Info( { "basic": {"name": "", "is_dir": True}, "details": {"type": int(ResourceType.directory)}, } ) obj = self._get_object(path, _key) info = self._info_from_object(obj, namespaces) return Info(info)
(self, path, namespaces=None)
18,466
fs.base
getmeta
Get meta information regarding a filesystem. Arguments: namespace (str): The meta namespace (defaults to ``"standard"``). Returns: dict: the meta information. Meta information is associated with a *namespace* which may be specified with the ``namespace`` parameter. The default namespace, ``"standard"``, contains common information regarding the filesystem's capabilities. Some filesystems may provide other namespaces which expose less common or implementation specific information. If a requested namespace is not supported by a filesystem, then an empty dictionary will be returned. The ``"standard"`` namespace supports the following keys: =================== ============================================ key Description ------------------- -------------------------------------------- case_insensitive `True` if this filesystem is case insensitive. invalid_path_chars A string containing the characters that may not be used on this filesystem. max_path_length Maximum number of characters permitted in a path, or `None` for no limit. max_sys_path_length Maximum number of characters permitted in a sys path, or `None` for no limit. network `True` if this filesystem requires a network. read_only `True` if this filesystem is read only. supports_rename `True` if this filesystem supports an `os.rename` operation. =================== ============================================ Most builtin filesystems will provide all these keys, and third- party filesystems should do so whenever possible, but a key may not be present if there is no way to know the value. Note: Meta information is constant for the lifetime of the filesystem, and may be cached.
def getmeta(self, namespace="standard"): # type: (Text) -> Mapping[Text, object] """Get meta information regarding a filesystem. Arguments: namespace (str): The meta namespace (defaults to ``"standard"``). Returns: dict: the meta information. Meta information is associated with a *namespace* which may be specified with the ``namespace`` parameter. The default namespace, ``"standard"``, contains common information regarding the filesystem's capabilities. Some filesystems may provide other namespaces which expose less common or implementation specific information. If a requested namespace is not supported by a filesystem, then an empty dictionary will be returned. The ``"standard"`` namespace supports the following keys: =================== ============================================ key Description ------------------- -------------------------------------------- case_insensitive `True` if this filesystem is case insensitive. invalid_path_chars A string containing the characters that may not be used on this filesystem. max_path_length Maximum number of characters permitted in a path, or `None` for no limit. max_sys_path_length Maximum number of characters permitted in a sys path, or `None` for no limit. network `True` if this filesystem requires a network. read_only `True` if this filesystem is read only. supports_rename `True` if this filesystem supports an `os.rename` operation. =================== ============================================ Most builtin filesystems will provide all these keys, and third- party filesystems should do so whenever possible, but a key may not be present if there is no way to know the value. Note: Meta information is constant for the lifetime of the filesystem, and may be cached. """ if namespace == "standard": meta = self._meta.copy() else: meta = {} return meta
(self, namespace='standard')
18,467
fs.base
getmodified
Get the timestamp of the last modifying access of a resource. Arguments: path (str): A path to a resource. Returns: datetime: The timestamp of the last modification. The *modified timestamp* of a file is the point in time that the file was last changed. Depending on the file system, it might only have limited accuracy.
def getmodified(self, path): # type: (Text) -> Optional[datetime] """Get the timestamp of the last modifying access of a resource. Arguments: path (str): A path to a resource. Returns: datetime: The timestamp of the last modification. The *modified timestamp* of a file is the point in time that the file was last changed. Depending on the file system, it might only have limited accuracy. """ return self.getinfo(path, namespaces=["details"]).modified
(self, path)
18,468
fs.base
getospath
Get the *system path* to a resource, in the OS' prefered encoding. Arguments: path (str): A path on the filesystem. Returns: str: the *system path* of the resource, if any. Raises: fs.errors.NoSysPath: If there is no corresponding system path. This method takes the output of `~getsyspath` and encodes it to the filesystem's prefered encoding. In Python3 this step is not required, as the `os` module will do it automatically. In Python2.7, the encoding step is required to support filenames on the filesystem that don't encode correctly. Note: If you want your code to work in Python2.7 and Python3 then use this method if you want to work with the OS filesystem outside of the OSFS interface.
def getospath(self, path): # type: (Text) -> bytes """Get the *system path* to a resource, in the OS' prefered encoding. Arguments: path (str): A path on the filesystem. Returns: str: the *system path* of the resource, if any. Raises: fs.errors.NoSysPath: If there is no corresponding system path. This method takes the output of `~getsyspath` and encodes it to the filesystem's prefered encoding. In Python3 this step is not required, as the `os` module will do it automatically. In Python2.7, the encoding step is required to support filenames on the filesystem that don't encode correctly. Note: If you want your code to work in Python2.7 and Python3 then use this method if you want to work with the OS filesystem outside of the OSFS interface. """ syspath = self.getsyspath(path) ospath = fsencode(syspath) return ospath
(self, path)
18,469
fs.base
getsize
Get the size (in bytes) of a resource. Arguments: path (str): A path to a resource. Returns: int: the *size* of the resource. Raises: fs.errors.ResourceNotFound: if ``path`` does not exist. The *size* of a file is the total number of readable bytes, which may not reflect the exact number of bytes of reserved disk space (or other storage medium). The size of a directory is the number of bytes of overhead use to store the directory entry.
def getsize(self, path): # type: (Text) -> int """Get the size (in bytes) of a resource. Arguments: path (str): A path to a resource. Returns: int: the *size* of the resource. Raises: fs.errors.ResourceNotFound: if ``path`` does not exist. The *size* of a file is the total number of readable bytes, which may not reflect the exact number of bytes of reserved disk space (or other storage medium). The size of a directory is the number of bytes of overhead use to store the directory entry. """ size = self.getdetails(path).size return size
(self, path)
18,470
fs.base
getsyspath
Get the *system path* of a resource. Arguments: path (str): A path on the filesystem. Returns: str: the *system path* of the resource, if any. Raises: fs.errors.NoSysPath: If there is no corresponding system path. A system path is one recognized by the OS, that may be used outside of PyFilesystem (in an application or a shell for example). This method will get the corresponding system path that would be referenced by ``path``. Not all filesystems have associated system paths. Network and memory based filesystems, for example, may not physically store data anywhere the OS knows about. It is also possible for some paths to have a system path, whereas others don't. This method will always return a str on Py3.* and unicode on Py2.7. See `~getospath` if you need to encode the path as bytes. If ``path`` doesn't have a system path, a `~fs.errors.NoSysPath` exception will be thrown. Note: A filesystem may return a system path even if no resource is referenced by that path -- as long as it can be certain what that system path would be.
def getsyspath(self, path): # type: (Text) -> Text """Get the *system path* of a resource. Arguments: path (str): A path on the filesystem. Returns: str: the *system path* of the resource, if any. Raises: fs.errors.NoSysPath: If there is no corresponding system path. A system path is one recognized by the OS, that may be used outside of PyFilesystem (in an application or a shell for example). This method will get the corresponding system path that would be referenced by ``path``. Not all filesystems have associated system paths. Network and memory based filesystems, for example, may not physically store data anywhere the OS knows about. It is also possible for some paths to have a system path, whereas others don't. This method will always return a str on Py3.* and unicode on Py2.7. See `~getospath` if you need to encode the path as bytes. If ``path`` doesn't have a system path, a `~fs.errors.NoSysPath` exception will be thrown. Note: A filesystem may return a system path even if no resource is referenced by that path -- as long as it can be certain what that system path would be. """ raise errors.NoSysPath(path=path)
(self, path)
18,471
fs.base
readtext
Get the contents of a file as a string. Arguments: path (str): A path to a readable file on the filesystem. encoding (str, optional): Encoding to use when reading contents in text mode (defaults to `None`, reading in binary mode). errors (str, optional): Unicode errors parameter. newline (str): Newlines parameter. Returns: str: file contents. Raises: fs.errors.ResourceNotFound: If ``path`` does not exist. Note: .. deprecated:: 2.2.0 Please use `~readtext`
def _new_name(method, old_name): """Return a method with a deprecation warning.""" # Looks suspiciously like a decorator, but isn't! @wraps(method) def _method(*args, **kwargs): warnings.warn( "method '{}' has been deprecated, please rename to '{}'".format( old_name, method.__name__ ), DeprecationWarning, ) return method(*args, **kwargs) deprecated_msg = """ Note: .. deprecated:: 2.2.0 Please use `~{}` """.format( method.__name__ ) if getattr(_method, "__doc__", None) is not None: _method.__doc__ += deprecated_msg return _method
(self, path, encoding=None, errors=None, newline='')
18,472
fs.base
gettype
Get the type of a resource. Arguments: path (str): A path on the filesystem. Returns: ~fs.enums.ResourceType: the type of the resource. Raises: fs.errors.ResourceNotFound: if ``path`` does not exist. A type of a resource is an integer that identifies the what the resource references. The standard type integers may be one of the values in the `~fs.enums.ResourceType` enumerations. The most common resource types, supported by virtually all filesystems are ``directory`` (1) and ``file`` (2), but the following types are also possible: =================== ====== ResourceType value ------------------- ------ unknown 0 directory 1 file 2 character 3 block_special_file 4 fifo 5 socket 6 symlink 7 =================== ====== Standard resource types are positive integers, negative values are reserved for implementation specific resource types.
def gettype(self, path): # type: (Text) -> ResourceType """Get the type of a resource. Arguments: path (str): A path on the filesystem. Returns: ~fs.enums.ResourceType: the type of the resource. Raises: fs.errors.ResourceNotFound: if ``path`` does not exist. A type of a resource is an integer that identifies the what the resource references. The standard type integers may be one of the values in the `~fs.enums.ResourceType` enumerations. The most common resource types, supported by virtually all filesystems are ``directory`` (1) and ``file`` (2), but the following types are also possible: =================== ====== ResourceType value ------------------- ------ unknown 0 directory 1 file 2 character 3 block_special_file 4 fifo 5 socket 6 symlink 7 =================== ====== Standard resource types are positive integers, negative values are reserved for implementation specific resource types. """ resource_type = self.getdetails(path).type return resource_type
(self, path)
18,473
miarec_s3fs.s3fs
geturl
null
def geturl(self, path, purpose="download"): _path = self.validatepath(path) _key = self._path_to_key(_path) if _path == "/": raise errors.NoURL(path, purpose) if purpose == "download": url = self.client.generate_presigned_url( ClientMethod="get_object", Params={"Bucket": self._bucket_name, "Key": _key}, ) return url else: raise errors.NoURL(path, purpose)
(self, path, purpose='download')
18,474
fs.base
hash
Get the hash of a file's contents. Arguments: path(str): A path on the filesystem. name(str): One of the algorithms supported by the `hashlib` module, e.g. `"md5"` or `"sha256"`. Returns: str: The hex digest of the hash. Raises: fs.errors.UnsupportedHash: If the requested hash is not supported. fs.errors.ResourceNotFound: If ``path`` does not exist. fs.errors.FileExpected: If ``path`` exists but is not a file.
def hash(self, path, name): # type: (Text, Text) -> Text """Get the hash of a file's contents. Arguments: path(str): A path on the filesystem. name(str): One of the algorithms supported by the `hashlib` module, e.g. `"md5"` or `"sha256"`. Returns: str: The hex digest of the hash. Raises: fs.errors.UnsupportedHash: If the requested hash is not supported. fs.errors.ResourceNotFound: If ``path`` does not exist. fs.errors.FileExpected: If ``path`` exists but is not a file. """ self.validatepath(path) try: hash_object = hashlib.new(name) except ValueError: raise errors.UnsupportedHash("hash '{}' is not supported".format(name)) with self.openbin(path) as binary_file: while True: chunk = binary_file.read(1024 * 1024) if not chunk: break hash_object.update(chunk) return hash_object.hexdigest()
(self, path, name)
18,475
fs.base
hassyspath
Check if a path maps to a system path. Arguments: path (str): A path on the filesystem. Returns: bool: `True` if the resource at ``path`` has a *syspath*.
def hassyspath(self, path): # type: (Text) -> bool """Check if a path maps to a system path. Arguments: path (str): A path on the filesystem. Returns: bool: `True` if the resource at ``path`` has a *syspath*. """ has_sys_path = True try: self.getsyspath(path) except errors.NoSysPath: has_sys_path = False return has_sys_path
(self, path)
18,476
fs.base
hasurl
Check if a path has a corresponding URL. Arguments: path (str): A path on the filesystem. purpose (str): A purpose parameter, as given in `~fs.base.FS.geturl`. Returns: bool: `True` if an URL for the given purpose exists.
def hasurl(self, path, purpose="download"): # type: (Text, Text) -> bool """Check if a path has a corresponding URL. Arguments: path (str): A path on the filesystem. purpose (str): A purpose parameter, as given in `~fs.base.FS.geturl`. Returns: bool: `True` if an URL for the given purpose exists. """ has_url = True try: self.geturl(path, purpose=purpose) except errors.NoURL: has_url = False return has_url
(self, path, purpose='download')
18,477
fs.base
isclosed
Check if the filesystem is closed.
def isclosed(self): # type: () -> bool """Check if the filesystem is closed.""" return getattr(self, "_closed", False)
(self)
18,478
miarec_s3fs.s3fs
isdir
null
def isdir(self, path): _path = self.validatepath(path) try: return self._getinfo(_path).is_dir except errors.ResourceNotFound: return False
(self, path)
18,479
miarec_s3fs.s3fs
isempty
null
def isempty(self, path): self.check() _path = self.validatepath(path) _key = self._path_to_dir_key(_path) response = self.client.list_objects( Bucket=self._bucket_name, Prefix=_key, MaxKeys=2 ) contents = response.get("Contents", ()) for obj in contents: if obj["Key"] != _key: return False return True
(self, path)
18,480
fs.base
isfile
Check if a path maps to an existing file. Arguments: path (str): A path on the filesystem. Returns: bool: `True` if ``path`` maps to a file.
def isfile(self, path): # type: (Text) -> bool """Check if a path maps to an existing file. Arguments: path (str): A path on the filesystem. Returns: bool: `True` if ``path`` maps to a file. """ try: return not self.getinfo(path).is_dir except errors.ResourceNotFound: return False
(self, path)
18,481
fs.base
islink
Check if a path maps to a symlink. Arguments: path (str): A path on the filesystem. Returns: bool: `True` if ``path`` maps to a symlink.
def islink(self, path): # type: (Text) -> bool """Check if a path maps to a symlink. Arguments: path (str): A path on the filesystem. Returns: bool: `True` if ``path`` maps to a symlink. """ self.getinfo(path) return False
(self, path)
18,482
miarec_s3fs.s3fs
listdir
null
def listdir(self, path): _path = self.validatepath(path) _s3_key = self._path_to_dir_key(_path) prefix_len = len(_s3_key) paginator = self.client.get_paginator("list_objects") with s3errors(path): _paginate = paginator.paginate( Bucket=self._bucket_name, Prefix=_s3_key, Delimiter=self.delimiter ) _directory = [] for result in _paginate: common_prefixes = result.get("CommonPrefixes", ()) for prefix in common_prefixes: _prefix = prefix.get("Prefix") _name = _prefix[prefix_len:] if _name: _directory.append(_name.rstrip(self.delimiter)) for obj in result.get("Contents", ()): name = obj["Key"][prefix_len:] if name: _directory.append(name) if not _directory: if not self.getinfo(_path).is_dir: raise errors.DirectoryExpected(path) return _directory
(self, path)
18,483
fs.base
lock
Get a context manager that *locks* the filesystem. Locking a filesystem gives a thread exclusive access to it. Other threads will block until the threads with the lock has left the context manager. Returns: threading.RLock: a lock specific to the filesystem instance. Example: >>> with my_fs.lock(): # May block ... # code here has exclusive access to the filesystem ... pass It is a good idea to put a lock around any operations that you would like to be *atomic*. For instance if you are copying files, and you don't want another thread to delete or modify anything while the copy is in progress. Locking with this method is only required for code that calls multiple filesystem methods. Individual methods are thread safe already, and don't need to be locked. Note: This only locks at the Python level. There is nothing to prevent other processes from modifying the filesystem outside of the filesystem instance.
def lock(self): # type: () -> RLock """Get a context manager that *locks* the filesystem. Locking a filesystem gives a thread exclusive access to it. Other threads will block until the threads with the lock has left the context manager. Returns: threading.RLock: a lock specific to the filesystem instance. Example: >>> with my_fs.lock(): # May block ... # code here has exclusive access to the filesystem ... pass It is a good idea to put a lock around any operations that you would like to be *atomic*. For instance if you are copying files, and you don't want another thread to delete or modify anything while the copy is in progress. Locking with this method is only required for code that calls multiple filesystem methods. Individual methods are thread safe already, and don't need to be locked. Note: This only locks at the Python level. There is nothing to prevent other processes from modifying the filesystem outside of the filesystem instance. """ return self._lock
(self)
18,484
miarec_s3fs.s3fs
makedir
null
def makedir(self, path, permissions=None, recreate=False): self.check() _path = self.validatepath(path) _key = self._path_to_dir_key(_path) if not self.isdir(dirname(_path)): raise errors.ResourceNotFound(path) try: self._getinfo(path) except errors.ResourceNotFound: pass else: if recreate: return self.opendir(_path) else: raise errors.DirectoryExists(path) with s3errors(path): _obj = self.s3.Object(self._bucket_name, _key) _obj.put(**self._get_upload_args(_key)) return SubFS(self, path)
(self, path, permissions=None, recreate=False)
18,485
fs.base
makedirs
Make a directory, and any missing intermediate directories. Arguments: path (str): Path to directory from root. permissions (~fs.permissions.Permissions, optional): Initial permissions, or `None` to use defaults. recreate (bool): If `False` (the default), attempting to create an existing directory will raise an error. Set to `True` to ignore existing directories. Returns: ~fs.subfs.SubFS: A sub-directory filesystem. Raises: fs.errors.DirectoryExists: if the path is already a directory, and ``recreate`` is `False`. fs.errors.DirectoryExpected: if one of the ancestors in the path is not a directory.
def makedirs( self, path, # type: Text permissions=None, # type: Optional[Permissions] recreate=False, # type: bool ): # type: (...) -> SubFS[FS] """Make a directory, and any missing intermediate directories. Arguments: path (str): Path to directory from root. permissions (~fs.permissions.Permissions, optional): Initial permissions, or `None` to use defaults. recreate (bool): If `False` (the default), attempting to create an existing directory will raise an error. Set to `True` to ignore existing directories. Returns: ~fs.subfs.SubFS: A sub-directory filesystem. Raises: fs.errors.DirectoryExists: if the path is already a directory, and ``recreate`` is `False`. fs.errors.DirectoryExpected: if one of the ancestors in the path is not a directory. """ self.check() with self._lock: dir_paths = tools.get_intermediate_dirs(self, path) for dir_path in dir_paths: try: self.makedir(dir_path, permissions=permissions) except errors.DirectoryExists: if not recreate: raise try: self.makedir(path, permissions=permissions) except errors.DirectoryExists: if not recreate: raise return self.opendir(path)
(self, path, permissions=None, recreate=False)
18,486
fs.base
match
Check if a name matches any of a list of wildcards. If a filesystem is case *insensitive* (such as Windows) then this method will perform a case insensitive match (i.e. ``*.py`` will match the same names as ``*.PY``). Otherwise the match will be case sensitive (``*.py`` and ``*.PY`` will match different names). Arguments: patterns (list, optional): A list of patterns, e.g. ``['*.py']``, or `None` to match everything. name (str): A file or directory name (not a path) Returns: bool: `True` if ``name`` matches any of the patterns. Raises: TypeError: If ``patterns`` is a single string instead of a list (or `None`). Example: >>> my_fs.match(['*.py'], '__init__.py') True >>> my_fs.match(['*.jpg', '*.png'], 'foo.gif') False Note: If ``patterns`` is `None` (or ``['*']``), then this method will always return `True`.
def match(self, patterns, name): # type: (Optional[Iterable[Text]], Text) -> bool """Check if a name matches any of a list of wildcards. If a filesystem is case *insensitive* (such as Windows) then this method will perform a case insensitive match (i.e. ``*.py`` will match the same names as ``*.PY``). Otherwise the match will be case sensitive (``*.py`` and ``*.PY`` will match different names). Arguments: patterns (list, optional): A list of patterns, e.g. ``['*.py']``, or `None` to match everything. name (str): A file or directory name (not a path) Returns: bool: `True` if ``name`` matches any of the patterns. Raises: TypeError: If ``patterns`` is a single string instead of a list (or `None`). Example: >>> my_fs.match(['*.py'], '__init__.py') True >>> my_fs.match(['*.jpg', '*.png'], 'foo.gif') False Note: If ``patterns`` is `None` (or ``['*']``), then this method will always return `True`. """ if patterns is None: return True if isinstance(patterns, six.text_type): raise TypeError("patterns must be a list or sequence") case_sensitive = not typing.cast( bool, self.getmeta().get("case_insensitive", False) ) matcher = wildcard.get_matcher(patterns, case_sensitive) return matcher(name)
(self, patterns, name)
18,487
miarec_s3fs.s3fs
move
null
def move(self, src_path, dst_path, overwrite=False, preserve_time=False): self.copy(src_path, dst_path, overwrite=overwrite, preserve_time=preserve_time) self.remove(src_path)
(self, src_path, dst_path, overwrite=False, preserve_time=False)
18,488
fs.base
movedir
Move directory ``src_path`` to ``dst_path``. Arguments: src_path (str): Path of source directory on the filesystem. dst_path (str): Path to destination directory. create (bool): If `True`, then ``dst_path`` will be created if it doesn't exist already (defaults to `False`). preserve_time (bool): If `True`, try to preserve mtime of the resources (defaults to `False`). Raises: fs.errors.ResourceNotFound: if ``dst_path`` does not exist, and ``create`` is `False`. fs.errors.DirectoryExpected: if ``src_path`` or one of its ancestors is not a directory.
def movedir(self, src_path, dst_path, create=False, preserve_time=False): # type: (Text, Text, bool, bool) -> None """Move directory ``src_path`` to ``dst_path``. Arguments: src_path (str): Path of source directory on the filesystem. dst_path (str): Path to destination directory. create (bool): If `True`, then ``dst_path`` will be created if it doesn't exist already (defaults to `False`). preserve_time (bool): If `True`, try to preserve mtime of the resources (defaults to `False`). Raises: fs.errors.ResourceNotFound: if ``dst_path`` does not exist, and ``create`` is `False`. fs.errors.DirectoryExpected: if ``src_path`` or one of its ancestors is not a directory. """ from .move import move_dir with self._lock: if not create and not self.exists(dst_path): raise errors.ResourceNotFound(dst_path) move_dir(self, src_path, self, dst_path, preserve_time=preserve_time)
(self, src_path, dst_path, create=False, preserve_time=False)
18,489
fs.base
open
Open a file. Arguments: path (str): A path to a file on the filesystem. mode (str): Mode to open the file object with (defaults to *r*). buffering (int): Buffering policy (-1 to use default buffering, 0 to disable buffering, 1 to select line buffering, of any positive integer to indicate a buffer size). encoding (str): Encoding for text files (defaults to ``utf-8``) errors (str, optional): What to do with unicode decode errors (see `codecs` module for more information). newline (str): Newline parameter. **options: keyword arguments for any additional information required by the filesystem (if any). Returns: io.IOBase: a *file-like* object. Raises: fs.errors.FileExpected: If the path is not a file. fs.errors.FileExists: If the file exists, and *exclusive mode* is specified (``x`` in the mode). fs.errors.ResourceNotFound: If the path does not exist.
def open( self, path, # type: Text mode="r", # type: Text buffering=-1, # type: int encoding=None, # type: Optional[Text] errors=None, # type: Optional[Text] newline="", # type: Text **options # type: Any ): # type: (...) -> IO """Open a file. Arguments: path (str): A path to a file on the filesystem. mode (str): Mode to open the file object with (defaults to *r*). buffering (int): Buffering policy (-1 to use default buffering, 0 to disable buffering, 1 to select line buffering, of any positive integer to indicate a buffer size). encoding (str): Encoding for text files (defaults to ``utf-8``) errors (str, optional): What to do with unicode decode errors (see `codecs` module for more information). newline (str): Newline parameter. **options: keyword arguments for any additional information required by the filesystem (if any). Returns: io.IOBase: a *file-like* object. Raises: fs.errors.FileExpected: If the path is not a file. fs.errors.FileExists: If the file exists, and *exclusive mode* is specified (``x`` in the mode). fs.errors.ResourceNotFound: If the path does not exist. """ validate_open_mode(mode) bin_mode = mode.replace("t", "") bin_file = self.openbin(path, mode=bin_mode, buffering=buffering) io_stream = iotools.make_stream( path, bin_file, mode=mode, buffering=buffering, encoding=encoding or "utf-8", errors=errors, newline=newline, **options ) return io_stream
(self, path, mode='r', buffering=-1, encoding=None, errors=None, newline='', **options)
18,490
miarec_s3fs.s3fs
openbin
null
def openbin(self, path, mode="rb", buffering=-1, **options): _mode = Mode(mode) _mode.validate_bin() self.check() _path = self.validatepath(path) _key = self._path_to_key(_path) if _mode.create: def on_close_create(s3file): """Called when the S3 file closes, to upload data.""" try: s3file.raw.seek(0) with s3errors(path): self.client.upload_fileobj( s3file.raw, self._bucket_name, _key, ExtraArgs=self._get_upload_args(_key), ) finally: s3file.raw.close() try: dir_path = dirname(_path) if dir_path != "/": _dir_key = self._path_to_dir_key(dir_path) self._get_object(dir_path, _dir_key) except errors.ResourceNotFound: raise errors.ResourceNotFound(path) try: info = self._getinfo(path) except errors.ResourceNotFound: pass else: if _mode.exclusive: raise errors.FileExists(path) if info.is_dir: raise errors.FileExpected(path) s3file = S3File.factory( path, _mode.to_platform_bin(), on_close=on_close_create ) if _mode.appending: try: with s3errors(path): self.client.download_fileobj( self._bucket_name, _key, s3file.raw, ExtraArgs=self.download_args, ) except errors.ResourceNotFound: pass else: s3file.seek(0, os.SEEK_END) return s3file if self.strict: info = self.getinfo(path) if info.is_dir: raise errors.FileExpected(path) def on_close(s3file): """Called when the S3 file closes, to upload the data.""" try: if _mode.writing: s3file.raw.seek(0, os.SEEK_SET) with s3errors(path): self.client.upload_fileobj( s3file.raw, self._bucket_name, _key, ExtraArgs=self._get_upload_args(_key), ) finally: s3file.raw.close() s3file = S3File.factory( path, _mode.to_platform_bin(), on_close=on_close ) with s3errors(path): self.client.download_fileobj( self._bucket_name, _key, s3file.raw, ExtraArgs=self.download_args ) s3file.seek(0, os.SEEK_SET) return s3file
(self, path, mode='rb', buffering=-1, **options)
18,491
fs.base
opendir
Get a filesystem object for a sub-directory. Arguments: path (str): Path to a directory on the filesystem. factory (callable, optional): A callable that when invoked with an FS instance and ``path`` will return a new FS object representing the sub-directory contents. If no ``factory`` is supplied then `~fs.subfs_class` will be used. Returns: ~fs.subfs.SubFS: A filesystem representing a sub-directory. Raises: fs.errors.ResourceNotFound: If ``path`` does not exist. fs.errors.DirectoryExpected: If ``path`` is not a directory.
def opendir( self, # type: _F path, # type: Text factory=None, # type: Optional[_OpendirFactory] ): # type: (...) -> SubFS[FS] # FIXME(@althonos): use generics here if possible """Get a filesystem object for a sub-directory. Arguments: path (str): Path to a directory on the filesystem. factory (callable, optional): A callable that when invoked with an FS instance and ``path`` will return a new FS object representing the sub-directory contents. If no ``factory`` is supplied then `~fs.subfs_class` will be used. Returns: ~fs.subfs.SubFS: A filesystem representing a sub-directory. Raises: fs.errors.ResourceNotFound: If ``path`` does not exist. fs.errors.DirectoryExpected: If ``path`` is not a directory. """ from .subfs import SubFS _factory = factory or self.subfs_class or SubFS if not self.getinfo(path).is_dir: raise errors.DirectoryExpected(path=path) return _factory(self, path)
(self, path, factory=None)
18,492
miarec_s3fs.s3fs
readbytes
null
def readbytes(self, path): self.check() if self.strict: info = self.getinfo(path) if not info.is_file: raise errors.FileExpected(path) _path = self.validatepath(path) _key = self._path_to_key(_path) bytes_file = io.BytesIO() with s3errors(path): self.client.download_fileobj( self._bucket_name, _key, bytes_file, ExtraArgs=self.download_args ) return bytes_file.getvalue()
(self, path)
18,493
fs.base
readtext
Get the contents of a file as a string. Arguments: path (str): A path to a readable file on the filesystem. encoding (str, optional): Encoding to use when reading contents in text mode (defaults to `None`, reading in binary mode). errors (str, optional): Unicode errors parameter. newline (str): Newlines parameter. Returns: str: file contents. Raises: fs.errors.ResourceNotFound: If ``path`` does not exist.
def readtext( self, path, # type: Text encoding=None, # type: Optional[Text] errors=None, # type: Optional[Text] newline="", # type: Text ): # type: (...) -> Text """Get the contents of a file as a string. Arguments: path (str): A path to a readable file on the filesystem. encoding (str, optional): Encoding to use when reading contents in text mode (defaults to `None`, reading in binary mode). errors (str, optional): Unicode errors parameter. newline (str): Newlines parameter. Returns: str: file contents. Raises: fs.errors.ResourceNotFound: If ``path`` does not exist. """ with closing( self.open( path, mode="rt", encoding=encoding, errors=errors, newline=newline ) ) as read_file: contents = read_file.read() return contents
(self, path, encoding=None, errors=None, newline='')
18,494
miarec_s3fs.s3fs
remove
null
def remove(self, path): self.check() _path = self.validatepath(path) _key = self._path_to_key(_path) if self.strict: info = self.getinfo(path) if info.is_dir: raise errors.FileExpected(path) with s3errors(path): self.client.delete_object(Bucket=self._bucket_name, Key=_key)
(self, path)
18,495
miarec_s3fs.s3fs
removedir
null
def removedir(self, path): self.check() _path = self.validatepath(path) if _path == "/": raise errors.RemoveRootError() info = self.getinfo(_path) if not info.is_dir: raise errors.DirectoryExpected(path) if not self.isempty(path): raise errors.DirectoryNotEmpty(path) _key = self._path_to_dir_key(_path) self.client.delete_object(Bucket=self._bucket_name, Key=_key)
(self, path)
18,496
fs.base
removetree
Recursively remove a directory and all its contents. This method is similar to `~fs.base.FS.removedir`, but will remove the contents of the directory if it is not empty. Arguments: dir_path (str): Path to a directory on the filesystem. Raises: fs.errors.ResourceNotFound: If ``dir_path`` does not exist. fs.errors.DirectoryExpected: If ``dir_path`` is not a directory. Caution: A filesystem should never delete its root folder, so ``FS.removetree("/")`` has different semantics: the contents of the root folder will be deleted, but the root will be untouched:: >>> home_fs = fs.open_fs("~") >>> home_fs.removetree("/") >>> home_fs.exists("/") True >>> home_fs.isempty("/") True Combined with `~fs.base.FS.opendir`, this can be used to clear a directory without removing the directory itself:: >>> home_fs = fs.open_fs("~") >>> home_fs.opendir("/Videos").removetree("/") >>> home_fs.exists("/Videos") True >>> home_fs.isempty("/Videos") True
def removetree(self, dir_path): # type: (Text) -> None """Recursively remove a directory and all its contents. This method is similar to `~fs.base.FS.removedir`, but will remove the contents of the directory if it is not empty. Arguments: dir_path (str): Path to a directory on the filesystem. Raises: fs.errors.ResourceNotFound: If ``dir_path`` does not exist. fs.errors.DirectoryExpected: If ``dir_path`` is not a directory. Caution: A filesystem should never delete its root folder, so ``FS.removetree("/")`` has different semantics: the contents of the root folder will be deleted, but the root will be untouched:: >>> home_fs = fs.open_fs("~") >>> home_fs.removetree("/") >>> home_fs.exists("/") True >>> home_fs.isempty("/") True Combined with `~fs.base.FS.opendir`, this can be used to clear a directory without removing the directory itself:: >>> home_fs = fs.open_fs("~") >>> home_fs.opendir("/Videos").removetree("/") >>> home_fs.exists("/Videos") True >>> home_fs.isempty("/Videos") True """ _dir_path = abspath(normpath(dir_path)) with self._lock: walker = walk.Walker(search="depth") gen_info = walker.info(self, _dir_path) for _path, info in gen_info: if info.is_dir: self.removedir(_path) else: self.remove(_path) if _dir_path != "/": self.removedir(dir_path)
(self, dir_path)
18,497
miarec_s3fs.s3fs
scandir
null
def scandir(self, path, namespaces=None, page=None): _path = self.validatepath(path) namespaces = namespaces or () _s3_key = self._path_to_dir_key(_path) prefix_len = len(_s3_key) info = self.getinfo(path) if not info.is_dir: raise errors.DirectoryExpected(path) paginator = self.client.get_paginator("list_objects") _paginate = paginator.paginate( Bucket=self._bucket_name, Prefix=_s3_key, Delimiter=self.delimiter ) def gen_info(): for result in _paginate: common_prefixes = result.get("CommonPrefixes", ()) for prefix in common_prefixes: _prefix = prefix.get("Prefix") _name = _prefix[prefix_len:] if _name: info = { "basic": { "name": _name.rstrip(self.delimiter), "is_dir": True, } } yield Info(info) for _obj in result.get("Contents", ()): name = _obj["Key"][prefix_len:] if name: with s3errors(path): obj = self.s3.Object(self._bucket_name, _obj["Key"]) info = self._info_from_object(obj, namespaces) yield Info(info) iter_info = iter(gen_info()) if page is not None: start, end = page iter_info = itertools.islice(iter_info, start, end) for info in iter_info: yield info
(self, path, namespaces=None, page=None)
18,498
fs.base
upload
Set a file to the contents of a binary file object. This method copies bytes from an open binary file to a file on the filesystem. If the destination exists, it will first be truncated. Arguments: path (str): A path on the filesystem. file (io.IOBase): a file object open for reading in binary mode. chunk_size (int, optional): Number of bytes to read at a time, if a simple copy is used, or `None` to use sensible default. **options: Implementation specific options required to open the source file. Raises: fs.errors.ResourceNotFound: If a parent directory of ``path`` does not exist. Note that the file object ``file`` will *not* be closed by this method. Take care to close it after this method completes (ideally with a context manager). Example: >>> with open('~/movies/starwars.mov', 'rb') as read_file: ... my_fs.upload('starwars.mov', read_file) Note: .. deprecated:: 2.2.0 Please use `~upload`
def _new_name(method, old_name): """Return a method with a deprecation warning.""" # Looks suspiciously like a decorator, but isn't! @wraps(method) def _method(*args, **kwargs): warnings.warn( "method '{}' has been deprecated, please rename to '{}'".format( old_name, method.__name__ ), DeprecationWarning, ) return method(*args, **kwargs) deprecated_msg = """ Note: .. deprecated:: 2.2.0 Please use `~{}` """.format( method.__name__ ) if getattr(_method, "__doc__", None) is not None: _method.__doc__ += deprecated_msg return _method
(self, path, file, chunk_size=None, **options)
18,499
fs.base
writebytes
Copy binary data to a file. Arguments: path (str): Destination path on the filesystem. contents (bytes): Data to be written. Raises: TypeError: if contents is not bytes. Note: .. deprecated:: 2.2.0 Please use `~writebytes`
def _new_name(method, old_name): """Return a method with a deprecation warning.""" # Looks suspiciously like a decorator, but isn't! @wraps(method) def _method(*args, **kwargs): warnings.warn( "method '{}' has been deprecated, please rename to '{}'".format( old_name, method.__name__ ), DeprecationWarning, ) return method(*args, **kwargs) deprecated_msg = """ Note: .. deprecated:: 2.2.0 Please use `~{}` """.format( method.__name__ ) if getattr(_method, "__doc__", None) is not None: _method.__doc__ += deprecated_msg return _method
(self, path, contents)
18,500
fs.base
writefile
Set a file to the contents of a file object. Arguments: path (str): A path on the filesystem. file (io.IOBase): A file object open for reading. encoding (str, optional): Encoding of destination file, defaults to `None` for binary. errors (str, optional): How encoding errors should be treated (same as `io.open`). newline (str): Newline parameter (same as `io.open`). This method is similar to `~FS.upload`, in that it copies data from a file-like object to a resource on the filesystem, but unlike ``upload``, this method also supports creating files in text-mode (if the ``encoding`` argument is supplied). Note that the file object ``file`` will *not* be closed by this method. Take care to close it after this method completes (ideally with a context manager). Example: >>> with open('myfile.txt') as read_file: ... my_fs.writefile('myfile.txt', read_file) Note: .. deprecated:: 2.2.0 Please use `~writefile`
def _new_name(method, old_name): """Return a method with a deprecation warning.""" # Looks suspiciously like a decorator, but isn't! @wraps(method) def _method(*args, **kwargs): warnings.warn( "method '{}' has been deprecated, please rename to '{}'".format( old_name, method.__name__ ), DeprecationWarning, ) return method(*args, **kwargs) deprecated_msg = """ Note: .. deprecated:: 2.2.0 Please use `~{}` """.format( method.__name__ ) if getattr(_method, "__doc__", None) is not None: _method.__doc__ += deprecated_msg return _method
(self, path, file, encoding=None, errors=None, newline='')
18,501
miarec_s3fs.s3fs
setinfo
null
def setinfo(self, path, info): self.getinfo(path)
(self, path, info)
18,502
fs.base
writetext
Create or replace a file with text. Arguments: path (str): Destination path on the filesystem. contents (str): Text to be written. encoding (str, optional): Encoding of destination file (defaults to ``'utf-8'``). errors (str, optional): How encoding errors should be treated (same as `io.open`). newline (str): Newline parameter (same as `io.open`). Raises: TypeError: if ``contents`` is not a unicode string. Note: .. deprecated:: 2.2.0 Please use `~writetext`
def _new_name(method, old_name): """Return a method with a deprecation warning.""" # Looks suspiciously like a decorator, but isn't! @wraps(method) def _method(*args, **kwargs): warnings.warn( "method '{}' has been deprecated, please rename to '{}'".format( old_name, method.__name__ ), DeprecationWarning, ) return method(*args, **kwargs) deprecated_msg = """ Note: .. deprecated:: 2.2.0 Please use `~{}` """.format( method.__name__ ) if getattr(_method, "__doc__", None) is not None: _method.__doc__ += deprecated_msg return _method
(self, path, contents, encoding='utf-8', errors=None, newline='')
18,503
fs.base
settimes
Set the accessed and modified time on a resource. Arguments: path: A path to a resource on the filesystem. accessed (datetime, optional): The accessed time, or `None` (the default) to use the current time. modified (datetime, optional): The modified time, or `None` (the default) to use the same time as the ``accessed`` parameter.
def settimes(self, path, accessed=None, modified=None): # type: (Text, Optional[datetime], Optional[datetime]) -> None """Set the accessed and modified time on a resource. Arguments: path: A path to a resource on the filesystem. accessed (datetime, optional): The accessed time, or `None` (the default) to use the current time. modified (datetime, optional): The modified time, or `None` (the default) to use the same time as the ``accessed`` parameter. """ details = {} # type: dict raw_info = {"details": details} details["accessed"] = ( time.time() if accessed is None else datetime_to_epoch(accessed) ) details["modified"] = ( details["accessed"] if modified is None else datetime_to_epoch(modified) ) self.setinfo(path, raw_info)
(self, path, accessed=None, modified=None)
18,504
fs.base
touch
Touch a file on the filesystem. Touching a file means creating a new file if ``path`` doesn't exist, or update accessed and modified times if the path does exist. This method is similar to the linux command of the same name. Arguments: path (str): A path to a file on the filesystem.
def touch(self, path): # type: (Text) -> None """Touch a file on the filesystem. Touching a file means creating a new file if ``path`` doesn't exist, or update accessed and modified times if the path does exist. This method is similar to the linux command of the same name. Arguments: path (str): A path to a file on the filesystem. """ with self._lock: now = time.time() if not self.create(path): raw_info = {"details": {"accessed": now, "modified": now}} self.setinfo(path, raw_info)
(self, path)
18,505
fs.base
tree
Render a tree view of the filesystem to stdout or a file. The parameters are passed to :func:`~fs.tree.render`. Keyword Arguments: path (str): The path of the directory to start rendering from (defaults to root folder, i.e. ``'/'``). file (io.IOBase): An open file-like object to render the tree, or `None` for stdout. encoding (str): Unicode encoding, or `None` to auto-detect. max_levels (int): Maximum number of levels to display, or `None` for no maximum. with_color (bool): Enable terminal color output, or `None` to auto-detect terminal. dirs_first (bool): Show directories first. exclude (list): Option list of directory patterns to exclude from the tree render. filter (list): Optional list of files patterns to match in the tree render.
def tree(self, **kwargs): # type: (**Any) -> None """Render a tree view of the filesystem to stdout or a file. The parameters are passed to :func:`~fs.tree.render`. Keyword Arguments: path (str): The path of the directory to start rendering from (defaults to root folder, i.e. ``'/'``). file (io.IOBase): An open file-like object to render the tree, or `None` for stdout. encoding (str): Unicode encoding, or `None` to auto-detect. max_levels (int): Maximum number of levels to display, or `None` for no maximum. with_color (bool): Enable terminal color output, or `None` to auto-detect terminal. dirs_first (bool): Show directories first. exclude (list): Option list of directory patterns to exclude from the tree render. filter (list): Optional list of files patterns to match in the tree render. """ from .tree import render render(self, **kwargs)
(self, **kwargs)
18,506
miarec_s3fs.s3fs
upload
null
def upload(self, path, file, chunk_size=None, **options): _path = self.validatepath(path) _key = self._path_to_key(_path) if self.strict: if not self.isdir(dirname(path)): raise errors.ResourceNotFound(path) try: info = self._getinfo(path) if info.is_dir: raise errors.FileExpected(path) except errors.ResourceNotFound: pass with s3errors(path): self.client.upload_fileobj( file, self._bucket_name, _key, ExtraArgs=self._get_upload_args(_key) )
(self, path, file, chunk_size=None, **options)
18,507
fs.base
validatepath
Validate a path, returning a normalized absolute path on sucess. Many filesystems have restrictions on the format of paths they support. This method will check that ``path`` is valid on the underlaying storage mechanism and throw a `~fs.errors.InvalidPath` exception if it is not. Arguments: path (str): A path. Returns: str: A normalized, absolute path. Raises: fs.errors.InvalidPath: If the path is invalid. fs.errors.FilesystemClosed: if the filesystem is closed. fs.errors.InvalidCharsInPath: If the path contains invalid characters.
def validatepath(self, path): # type: (Text) -> Text """Validate a path, returning a normalized absolute path on sucess. Many filesystems have restrictions on the format of paths they support. This method will check that ``path`` is valid on the underlaying storage mechanism and throw a `~fs.errors.InvalidPath` exception if it is not. Arguments: path (str): A path. Returns: str: A normalized, absolute path. Raises: fs.errors.InvalidPath: If the path is invalid. fs.errors.FilesystemClosed: if the filesystem is closed. fs.errors.InvalidCharsInPath: If the path contains invalid characters. """ self.check() if isinstance(path, bytes): raise TypeError( "paths must be unicode (not str)" if six.PY2 else "paths must be str (not bytes)" ) meta = self.getmeta() invalid_chars = typing.cast(six.text_type, meta.get("invalid_path_chars")) if invalid_chars: if set(path).intersection(invalid_chars): raise errors.InvalidCharsInPath(path) max_sys_path_length = typing.cast(int, meta.get("max_sys_path_length", -1)) if max_sys_path_length != -1: try: sys_path = self.getsyspath(path) except errors.NoSysPath: # pragma: no cover pass else: if len(sys_path) > max_sys_path_length: _msg = "path too long (max {max_chars} characters in sys path)" msg = _msg.format(max_chars=max_sys_path_length) raise errors.InvalidPath(path, msg=msg) path = abspath(normpath(path)) return path
(self, path)
18,508
miarec_s3fs.s3fs
writebytes
null
def writebytes(self, path, contents): if not isinstance(contents, bytes): raise TypeError("contents must be bytes") _path = self.validatepath(path) _key = self._path_to_key(_path) if self.strict: if not self.isdir(dirname(path)): raise errors.ResourceNotFound(path) try: info = self._getinfo(path) if info.is_dir: raise errors.FileExpected(path) except errors.ResourceNotFound: pass bytes_file = io.BytesIO(contents) with s3errors(path): self.client.upload_fileobj( bytes_file, self._bucket_name, _key, ExtraArgs=self._get_upload_args(_key), )
(self, path, contents)
18,509
fs.base
writefile
Set a file to the contents of a file object. Arguments: path (str): A path on the filesystem. file (io.IOBase): A file object open for reading. encoding (str, optional): Encoding of destination file, defaults to `None` for binary. errors (str, optional): How encoding errors should be treated (same as `io.open`). newline (str): Newline parameter (same as `io.open`). This method is similar to `~FS.upload`, in that it copies data from a file-like object to a resource on the filesystem, but unlike ``upload``, this method also supports creating files in text-mode (if the ``encoding`` argument is supplied). Note that the file object ``file`` will *not* be closed by this method. Take care to close it after this method completes (ideally with a context manager). Example: >>> with open('myfile.txt') as read_file: ... my_fs.writefile('myfile.txt', read_file)
def writefile( self, path, # type: Text file, # type: IO encoding=None, # type: Optional[Text] errors=None, # type: Optional[Text] newline="", # type: Text ): # type: (...) -> None """Set a file to the contents of a file object. Arguments: path (str): A path on the filesystem. file (io.IOBase): A file object open for reading. encoding (str, optional): Encoding of destination file, defaults to `None` for binary. errors (str, optional): How encoding errors should be treated (same as `io.open`). newline (str): Newline parameter (same as `io.open`). This method is similar to `~FS.upload`, in that it copies data from a file-like object to a resource on the filesystem, but unlike ``upload``, this method also supports creating files in text-mode (if the ``encoding`` argument is supplied). Note that the file object ``file`` will *not* be closed by this method. Take care to close it after this method completes (ideally with a context manager). Example: >>> with open('myfile.txt') as read_file: ... my_fs.writefile('myfile.txt', read_file) """ mode = "wb" if encoding is None else "wt" with self._lock: with self.open( path, mode=mode, encoding=encoding, errors=errors, newline=newline ) as dst_file: tools.copy_file_data(file, dst_file)
(self, path, file, encoding=None, errors=None, newline='')
18,510
fs.base
writetext
Create or replace a file with text. Arguments: path (str): Destination path on the filesystem. contents (str): Text to be written. encoding (str, optional): Encoding of destination file (defaults to ``'utf-8'``). errors (str, optional): How encoding errors should be treated (same as `io.open`). newline (str): Newline parameter (same as `io.open`). Raises: TypeError: if ``contents`` is not a unicode string.
def writetext( self, path, # type: Text contents, # type: Text encoding="utf-8", # type: Text errors=None, # type: Optional[Text] newline="", # type: Text ): # type: (...) -> None """Create or replace a file with text. Arguments: path (str): Destination path on the filesystem. contents (str): Text to be written. encoding (str, optional): Encoding of destination file (defaults to ``'utf-8'``). errors (str, optional): How encoding errors should be treated (same as `io.open`). newline (str): Newline parameter (same as `io.open`). Raises: TypeError: if ``contents`` is not a unicode string. """ if not isinstance(contents, six.text_type): raise TypeError("contents must be unicode") with closing( self.open( path, mode="wt", encoding=encoding, errors=errors, newline=newline ) ) as write_file: write_file.write(contents)
(self, path, contents, encoding='utf-8', errors=None, newline='')
18,519
ua_generator
generate
null
def generate(**kwargs): return user_agent.UserAgent(**kwargs)
(**kwargs)
18,524
reportlab
_fake_import
null
def _fake_import(fn,name): from importlib.util import spec_from_loader, module_from_spec from importlib.machinery import SourceFileLoader spec = spec_from_loader(name, SourceFileLoader(name, fn)) module = module_from_spec(spec) try: spec.loader.exec_module(module) except FileNotFoundError: raise ImportError('file %s not found' % ascii(fn)) sys.modules[name] = module
(fn, name)
18,525
reportlab
cmp
null
def cmp(a,b): return -1 if a<b else (1 if a>b else 0)
(a, b)
18,528
grafana_client.api
AsyncGrafanaApi
null
class AsyncGrafanaApi(GrafanaApi): def __init__( self, auth=None, host="localhost", port=None, url_path_prefix="", protocol="http", verify=True, timeout=DEFAULT_TIMEOUT, user_agent: str = None, organization_id: int = None, ): self.client = AsyncGrafanaClient( auth, host=host, port=port, url_path_prefix=url_path_prefix, protocol=protocol, verify=verify, timeout=timeout, user_agent=user_agent, organization_id=organization_id, ) self.url = None self.admin = AsyncAdmin(self.client) self.alerting = AsyncAlerting(self.client) self.alertingprovisioning = AsyncAlertingProvisioning(self.client) self.dashboard = AsyncDashboard(self.client, self) self.dashboard_versions = AsyncDashboardVersions(self.client) self.datasource = AsyncDatasource(self.client, self) self.folder = AsyncFolder(self.client) self.health = AsyncHealth(self.client) self.organization = AsyncOrganization(self.client) self.organizations = AsyncOrganizations(self.client, self) self.search = AsyncSearch(self.client) self.user = AsyncUser(self.client) self.users = AsyncUsers(self.client) self.rbac = AsyncRbac(self.client) self.teams = AsyncTeams(self.client, self) self.annotations = AsyncAnnotations(self.client) self.snapshots = AsyncSnapshots(self.client) self.notifications = AsyncNotifications(self.client) self.plugin = AsyncPlugin(self.client) self.serviceaccount = AsyncServiceAccount(self.client) self.libraryelement = AsyncLibraryElement(self.client, self) self._grafana_info = None async def connect(self): try: self._grafana_info = await self.health.check() except niquests.exceptions.ConnectionError as ex: # pragma: no cover logger.critical(f"Unable to connect to Grafana at {self.url or self.client.url_host}: {ex}") raise logger.info(f"Connected to Grafana at {self.url}: {self._grafana_info}") return self._grafana_info @property async def version(self): if not self._grafana_info: self._grafana_info = await self.health.check() version = self._grafana_info["version"] logger.info(f"Inquired Grafana version: {version}") return version
(auth=None, host='localhost', port=None, url_path_prefix='', protocol='http', verify=True, timeout=5.0, user_agent: str = None, organization_id: int = None)
18,529
grafana_client.api
__init__
null
def __init__( self, auth=None, host="localhost", port=None, url_path_prefix="", protocol="http", verify=True, timeout=DEFAULT_TIMEOUT, user_agent: str = None, organization_id: int = None, ): self.client = AsyncGrafanaClient( auth, host=host, port=port, url_path_prefix=url_path_prefix, protocol=protocol, verify=verify, timeout=timeout, user_agent=user_agent, organization_id=organization_id, ) self.url = None self.admin = AsyncAdmin(self.client) self.alerting = AsyncAlerting(self.client) self.alertingprovisioning = AsyncAlertingProvisioning(self.client) self.dashboard = AsyncDashboard(self.client, self) self.dashboard_versions = AsyncDashboardVersions(self.client) self.datasource = AsyncDatasource(self.client, self) self.folder = AsyncFolder(self.client) self.health = AsyncHealth(self.client) self.organization = AsyncOrganization(self.client) self.organizations = AsyncOrganizations(self.client, self) self.search = AsyncSearch(self.client) self.user = AsyncUser(self.client) self.users = AsyncUsers(self.client) self.rbac = AsyncRbac(self.client) self.teams = AsyncTeams(self.client, self) self.annotations = AsyncAnnotations(self.client) self.snapshots = AsyncSnapshots(self.client) self.notifications = AsyncNotifications(self.client) self.plugin = AsyncPlugin(self.client) self.serviceaccount = AsyncServiceAccount(self.client) self.libraryelement = AsyncLibraryElement(self.client, self) self._grafana_info = None
(self, auth=None, host='localhost', port=None, url_path_prefix='', protocol='http', verify=True, timeout=5.0, user_agent: Optional[str] = None, organization_id: Optional[int] = None)
18,531
grafana_client.api
GrafanaApi
null
class GrafanaApi: def __init__( self, auth=None, host="localhost", port=None, url_path_prefix="", protocol="http", verify=True, timeout=DEFAULT_TIMEOUT, user_agent: str = None, organization_id: int = None, ): self.client = GrafanaClient( auth, host=host, port=port, url_path_prefix=url_path_prefix, protocol=protocol, verify=verify, timeout=timeout, user_agent=user_agent, organization_id=organization_id, ) self.url = None self.admin = Admin(self.client) self.alerting = Alerting(self.client) self.alertingprovisioning = AlertingProvisioning(self.client) self.dashboard = Dashboard(self.client, self) self.dashboard_versions = DashboardVersions(self.client) self.datasource = Datasource(self.client, self) self.folder = Folder(self.client) self.health = Health(self.client) self.organization = Organization(self.client) self.organizations = Organizations(self.client, self) self.search = Search(self.client) self.user = User(self.client) self.users = Users(self.client) self.rbac = Rbac(self.client) self.teams = Teams(self.client, self) self.annotations = Annotations(self.client) self.snapshots = Snapshots(self.client) self.notifications = Notifications(self.client) self.plugin = Plugin(self.client) self.serviceaccount = ServiceAccount(self.client) self.libraryelement = LibraryElement(self.client, self) self._grafana_info = None def connect(self): try: self._grafana_info = self.health.check() except niquests.exceptions.ConnectionError as ex: logger.critical(f"Unable to connect to Grafana at {self.url or self.client.url_host}: {ex}") raise logger.info(f"Connected to Grafana at {self.url}: {self._grafana_info}") return self._grafana_info @property def version(self): if not self._grafana_info: self._grafana_info = self.health.check() version = self._grafana_info["version"] logger.info(f"Inquired Grafana version: {version}") return version @classmethod def from_url( cls, url: str = None, credential: Union[str, Tuple[str, str], niquests.auth.AuthBase] = None, timeout: Union[float, Tuple[float, float]] = DEFAULT_TIMEOUT, ): """ Factory method to create a `GrafanaApi` instance from a URL. Accepts an optional credential, which is either an authentication token, or a tuple of (username, password). """ # Sanity checks and defaults. if url is None: url = "http://admin:admin@localhost:3000" if credential is not None and not isinstance(credential, (str, Tuple, niquests.auth.AuthBase)): raise TypeError(f"Argument 'credential' has wrong type: {type(credential)}") original_url = url url = urlparse(url) # Use username and password from URL. if credential is None and url.username: credential = (url.username, url.password) # Optionally turn off SSL verification. verify = as_bool(parse_qs(url.query).get("verify", [True])[0]) if verify is False: warnings.filterwarnings("ignore", category=InsecureRequestWarning) grafana = cls( credential, protocol=url.scheme, host=url.hostname, port=url.port, url_path_prefix=url.path.lstrip("/"), verify=verify, timeout=timeout, ) grafana.url = original_url return grafana @classmethod def from_env(cls, timeout: Union[float, Tuple[float, float]] = None): """ Factory method to create a `GrafanaApi` instance from environment variables. """ if timeout is None: if "GRAFANA_TIMEOUT" in os.environ: try: timeout = float(os.environ["GRAFANA_TIMEOUT"]) except Exception as ex: raise ValueError( f"Unable to parse invalid `float` value from " f"`GRAFANA_TIMEOUT` environment variable: {ex}" ) if timeout is None: timeout = DEFAULT_TIMEOUT return cls.from_url( url=os.environ.get("GRAFANA_URL"), credential=os.environ.get("GRAFANA_TOKEN"), timeout=timeout )
(auth=None, host='localhost', port=None, url_path_prefix='', protocol='http', verify=True, timeout=5.0, user_agent: str = None, organization_id: int = None)
18,532
grafana_client.api
__init__
null
def __init__( self, auth=None, host="localhost", port=None, url_path_prefix="", protocol="http", verify=True, timeout=DEFAULT_TIMEOUT, user_agent: str = None, organization_id: int = None, ): self.client = GrafanaClient( auth, host=host, port=port, url_path_prefix=url_path_prefix, protocol=protocol, verify=verify, timeout=timeout, user_agent=user_agent, organization_id=organization_id, ) self.url = None self.admin = Admin(self.client) self.alerting = Alerting(self.client) self.alertingprovisioning = AlertingProvisioning(self.client) self.dashboard = Dashboard(self.client, self) self.dashboard_versions = DashboardVersions(self.client) self.datasource = Datasource(self.client, self) self.folder = Folder(self.client) self.health = Health(self.client) self.organization = Organization(self.client) self.organizations = Organizations(self.client, self) self.search = Search(self.client) self.user = User(self.client) self.users = Users(self.client) self.rbac = Rbac(self.client) self.teams = Teams(self.client, self) self.annotations = Annotations(self.client) self.snapshots = Snapshots(self.client) self.notifications = Notifications(self.client) self.plugin = Plugin(self.client) self.serviceaccount = ServiceAccount(self.client) self.libraryelement = LibraryElement(self.client, self) self._grafana_info = None
(self, auth=None, host='localhost', port=None, url_path_prefix='', protocol='http', verify=True, timeout=5.0, user_agent: Optional[str] = None, organization_id: Optional[int] = None)
18,533
grafana_client.api
connect
null
def connect(self): try: self._grafana_info = self.health.check() except niquests.exceptions.ConnectionError as ex: logger.critical(f"Unable to connect to Grafana at {self.url or self.client.url_host}: {ex}") raise logger.info(f"Connected to Grafana at {self.url}: {self._grafana_info}") return self._grafana_info
(self)
18,534
grafana_client.client
HeaderAuth
null
class HeaderAuth(niquests.auth.AuthBase): def __init__(self, name, value): self.name = name self.value = value def __call__(self, request): request.headers.update({self.name: self.value}) return request
(name, value)
18,535
grafana_client.client
__call__
null
def __call__(self, request): request.headers.update({self.name: self.value}) return request
(self, request)
18,536
grafana_client.client
__init__
null
def __init__(self, name, value): self.name = name self.value = value
(self, name, value)
18,539
grafana_client.client
TokenAuth
null
class TokenAuth(niquests.auth.AuthBase): def __init__(self, token): self.token = token def __call__(self, request): request.headers.update({"Authorization": f"Bearer {self.token}"}) return request
(token)
18,540
grafana_client.client
__call__
null
def __call__(self, request): request.headers.update({"Authorization": f"Bearer {self.token}"}) return request
(self, request)
18,541
grafana_client.client
__init__
null
def __init__(self, token): self.token = token
(self, token)
18,549
traceback2
FrameSummary
A single frame from a traceback. - :attr:`filename` The filename for the frame. - :attr:`lineno` The line within filename for the frame that was active when the frame was captured. - :attr:`name` The name of the function or method that was executing when the frame was captured. - :attr:`line` The text from the linecache module for the of code that was running when the frame was captured. - :attr:`locals` Either None if locals were not supplied, or a dict mapping the name to the repr() of the variable.
class FrameSummary: """A single frame from a traceback. - :attr:`filename` The filename for the frame. - :attr:`lineno` The line within filename for the frame that was active when the frame was captured. - :attr:`name` The name of the function or method that was executing when the frame was captured. - :attr:`line` The text from the linecache module for the of code that was running when the frame was captured. - :attr:`locals` Either None if locals were not supplied, or a dict mapping the name to the repr() of the variable. """ __slots__ = ('filename', 'lineno', 'name', '_line', 'locals') def __init__(self, filename, lineno, name, lookup_line=True, locals=None, line=None): """Construct a FrameSummary. :param lookup_line: If True, `linecache` is consulted for the source code line. Otherwise, the line will be looked up when first needed. :param locals: If supplied the frame locals, which will be captured as object representations. :param line: If provided, use this instead of looking up the line in the linecache. """ self.filename = filename self.lineno = lineno self.name = name self._line = line if lookup_line: self.line self.locals = \ dict((k, repr(v)) for k, v in locals.items()) if locals else None def __eq__(self, other): return (self.filename == other.filename and self.lineno == other.lineno and self.name == other.name and self.locals == other.locals) def __getitem__(self, pos): return (self.filename, self.lineno, self.name, self.line)[pos] def __iter__(self): return iter([self.filename, self.lineno, self.name, self.line]) def __repr__(self): return "<FrameSummary file {filename}, line {lineno} in {name}>".format( filename=self.filename, lineno=self.lineno, name=self.name) @property def line(self): if self._line is None: self._line = linecache.getline(self.filename, self.lineno).strip() return self._line
(filename, lineno, name, lookup_line=True, locals=None, line=None)
18,550
traceback2
__eq__
null
def __eq__(self, other): return (self.filename == other.filename and self.lineno == other.lineno and self.name == other.name and self.locals == other.locals)
(self, other)
18,551
traceback2
__getitem__
null
def __getitem__(self, pos): return (self.filename, self.lineno, self.name, self.line)[pos]
(self, pos)
18,552
traceback2
__init__
Construct a FrameSummary. :param lookup_line: If True, `linecache` is consulted for the source code line. Otherwise, the line will be looked up when first needed. :param locals: If supplied the frame locals, which will be captured as object representations. :param line: If provided, use this instead of looking up the line in the linecache.
def __init__(self, filename, lineno, name, lookup_line=True, locals=None, line=None): """Construct a FrameSummary. :param lookup_line: If True, `linecache` is consulted for the source code line. Otherwise, the line will be looked up when first needed. :param locals: If supplied the frame locals, which will be captured as object representations. :param line: If provided, use this instead of looking up the line in the linecache. """ self.filename = filename self.lineno = lineno self.name = name self._line = line if lookup_line: self.line self.locals = \ dict((k, repr(v)) for k, v in locals.items()) if locals else None
(self, filename, lineno, name, lookup_line=True, locals=None, line=None)
18,553
traceback2
__iter__
null
def __iter__(self): return iter([self.filename, self.lineno, self.name, self.line])
(self)
18,554
traceback2
__repr__
null
def __repr__(self): return "<FrameSummary file {filename}, line {lineno} in {name}>".format( filename=self.filename, lineno=self.lineno, name=self.name)
(self)
18,555
traceback2
StackSummary
A stack of frames.
class StackSummary(list): """A stack of frames.""" @classmethod def extract(klass, frame_gen, limit=None, lookup_lines=True, capture_locals=False): """Create a StackSummary from a traceback or stack object. :param frame_gen: A generator that yields (frame, lineno) tuples to include in the stack. :param limit: None to include all frames or the number of frames to include. :param lookup_lines: If True, lookup lines for each frame immediately, otherwise lookup is deferred until the frame is rendered. :param capture_locals: If True, the local variables from each frame will be captured as object representations into the FrameSummary. """ if limit is None: limit = getattr(sys, 'tracebacklimit', None) result = klass() fnames = set() for pos, (f, lineno) in enumerate(frame_gen): if limit is not None and pos >= limit: break co = f.f_code filename = co.co_filename name = co.co_name fnames.add(filename) linecache.lazycache(filename, f.f_globals) # Must defer line lookups until we have called checkcache. if capture_locals: f_locals = f.f_locals else: f_locals = None result.append(FrameSummary( filename, lineno, name, lookup_line=False, locals=f_locals)) for filename in fnames: linecache.checkcache(filename) # If immediate lookup was desired, trigger lookups now. if lookup_lines: for f in result: f.line return result @classmethod def from_list(klass, a_list): """Create a StackSummary from a simple list of tuples. This method supports the older Python API. Each tuple should be a 4-tuple with (filename, lineno, name, line) elements. """ if isinstance(a_list, StackSummary): return StackSummary(a_list) result = StackSummary() for filename, lineno, name, line in a_list: result.append(FrameSummary(filename, lineno, name, line=line)) return result def format(self): """Format the stack ready for printing. Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines. """ result = [] for frame in self: row = [] row.append(u(' File "{0}", line {1}, in {2}\n').format( _some_fs_str(frame.filename), frame.lineno, frame.name)) if frame.line: row.append(u(' {0}\n').format(frame.line.strip())) if frame.locals: for name, value in sorted(frame.locals.items()): row.append(u(' {name} = {value}\n').format(name=name, value=value)) result.append(u('').join(row)) return result
(iterable=(), /)
18,556
traceback2
format
Format the stack ready for printing. Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines.
def format(self): """Format the stack ready for printing. Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines. """ result = [] for frame in self: row = [] row.append(u(' File "{0}", line {1}, in {2}\n').format( _some_fs_str(frame.filename), frame.lineno, frame.name)) if frame.line: row.append(u(' {0}\n').format(frame.line.strip())) if frame.locals: for name, value in sorted(frame.locals.items()): row.append(u(' {name} = {value}\n').format(name=name, value=value)) result.append(u('').join(row)) return result
(self)
18,557
traceback2
TracebackException
An exception ready for rendering. The traceback module captures enough attributes from the original exception to this intermediary form to ensure that no references are held, while still being able to fully print or format it. Use `from_exception` to create TracebackException instances from exception objects, or the constructor to create TracebackException instances from individual components. - :attr:`__cause__` A TracebackException of the original *__cause__*. - :attr:`__context__` A TracebackException of the original *__context__*. - :attr:`__suppress_context__` The *__suppress_context__* value from the original exception. - :attr:`stack` A `StackSummary` representing the traceback. - :attr:`exc_type` The class of the original traceback. - :attr:`filename` For syntax errors - the filename where the error occured. - :attr:`lineno` For syntax errors - the linenumber where the error occured. - :attr:`text` For syntax errors - the text where the error occured. - :attr:`offset` For syntax errors - the offset into the text where the error occured. - :attr:`msg` For syntax errors - the compiler error message.
class TracebackException: """An exception ready for rendering. The traceback module captures enough attributes from the original exception to this intermediary form to ensure that no references are held, while still being able to fully print or format it. Use `from_exception` to create TracebackException instances from exception objects, or the constructor to create TracebackException instances from individual components. - :attr:`__cause__` A TracebackException of the original *__cause__*. - :attr:`__context__` A TracebackException of the original *__context__*. - :attr:`__suppress_context__` The *__suppress_context__* value from the original exception. - :attr:`stack` A `StackSummary` representing the traceback. - :attr:`exc_type` The class of the original traceback. - :attr:`filename` For syntax errors - the filename where the error occured. - :attr:`lineno` For syntax errors - the linenumber where the error occured. - :attr:`text` For syntax errors - the text where the error occured. - :attr:`offset` For syntax errors - the offset into the text where the error occured. - :attr:`msg` For syntax errors - the compiler error message. """ def __init__(self, exc_type, exc_value, exc_traceback, limit=None, lookup_lines=True, capture_locals=False, _seen=None): # NB: we need to accept exc_traceback, exc_value, exc_traceback to # permit backwards compat with the existing API, otherwise we # need stub thunk objects just to glue it together. # Handle loops in __cause__ or __context__. if _seen is None: _seen = set() _seen.add(exc_value) # Gracefully handle (the way Python 2.4 and earlier did) the case of # being called with no type or value (None, None, None). if (exc_value and getattr(exc_value, '__cause__', None) is not None and exc_value.__cause__ not in _seen): cause = TracebackException( type(exc_value.__cause__), exc_value.__cause__, exc_value.__cause__.__traceback__, limit=limit, lookup_lines=False, capture_locals=capture_locals, _seen=_seen) else: cause = None if (exc_value and getattr(exc_value, '__context__', None) is not None and exc_value.__context__ not in _seen): context = TracebackException( type(exc_value.__context__), exc_value.__context__, exc_value.__context__.__traceback__, limit=limit, lookup_lines=False, capture_locals=capture_locals, _seen=_seen) else: context = None self.__cause__ = cause self.__context__ = context self.__suppress_context__ = \ getattr(exc_value, '__suppress_context__', False) if exc_value else False # TODO: locals. self.stack = StackSummary.extract( walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines, capture_locals=capture_locals) self.exc_type = exc_type # Capture now to permit freeing resources: only complication is in the # unofficial API _format_final_exc_line self._str = _some_str(exc_value) if exc_type and issubclass(exc_type, SyntaxError): # Handle SyntaxError's specially self.filename = exc_value.filename self.lineno = str(exc_value.lineno) self.text = exc_value.text self.offset = exc_value.offset self.msg = exc_value.msg if lookup_lines: self._load_lines() @classmethod def from_exception(self, exc, *args, **kwargs): """Create a TracebackException from an exception. Only useful in Python 3 specific code. """ return TracebackException( type(exc), exc, exc.__traceback__, *args, **kwargs) def _load_lines(self): """Private API. force all lines in the stack to be loaded.""" for frame in self.stack: frame.line if self.__context__: self.__context__._load_lines() if self.__cause__: self.__cause__._load_lines() def __eq__(self, other): return self.__dict__ == other.__dict__ def __str__(self): return self._str def format_exception_only(self): """Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emites several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. """ if self.exc_type is None: yield _format_final_exc_line(None, self._str) return stype = getattr(self.exc_type, '__qualname__', self.exc_type.__name__) smod = u(self.exc_type.__module__) if smod not in ("__main__", "builtins", "exceptions"): stype = smod + u('.') + stype if not issubclass(self.exc_type, SyntaxError): yield _format_final_exc_line(stype, self._str) return # It was a syntax error; show exactly where the problem was found. filename = _some_fs_str(self.filename) or u("<string>") lineno = str(self.lineno) or u('?') yield u(' File "{0}", line {1}\n').format(filename, lineno) badline = None if self.text is not None: if type(self.text) is bytes: # Not decoded - get the line via linecache which will decode # for us. if self.lineno: badline = linecache.getline(filename, int(lineno)) if not badline: # But we can't for some reason, so fallback to attempting a # u cast. badline = u(self.text) else: badline = self.text offset = self.offset if badline is not None: yield u(' {0}\n').format(badline.strip()) if offset is not None: caretspace = badline.rstrip('\n') offset = min(len(caretspace), offset) - 1 caretspace = caretspace[:offset].lstrip() # non-space whitespace (likes tabs) must be kept for alignment caretspace = ((c.isspace() and c or ' ') for c in caretspace) yield u(' {0}^\n').format(''.join(caretspace)) msg = self.msg or u("<no detail available>") yield u("{0}: {1}\n").format(stype, msg) def format(self, chain=True): """Format the exception. If chain is not *True*, *__cause__* and *__context__* will not be formatted. The return value is a generator of strings, each ending in a newline and some containing internal newlines. `print_exception` is a wrapper around this method which just prints the lines to a file. The message indicating which exception occurred is always the last string in the output. """ if chain: if self.__cause__ is not None: for line in self.__cause__.format(chain=chain): yield line yield _cause_message elif (self.__context__ is not None and not self.__suppress_context__): for line in self.__context__.format(chain=chain): yield line yield _context_message yield u('Traceback (most recent call last):\n') for line in self.stack.format(): yield line for line in self.format_exception_only(): yield line
(exc_type, exc_value, exc_traceback, limit=None, lookup_lines=True, capture_locals=False, _seen=None)
18,558
traceback2
__eq__
null
def __eq__(self, other): return self.__dict__ == other.__dict__
(self, other)
18,559
traceback2
__init__
null
def __init__(self, exc_type, exc_value, exc_traceback, limit=None, lookup_lines=True, capture_locals=False, _seen=None): # NB: we need to accept exc_traceback, exc_value, exc_traceback to # permit backwards compat with the existing API, otherwise we # need stub thunk objects just to glue it together. # Handle loops in __cause__ or __context__. if _seen is None: _seen = set() _seen.add(exc_value) # Gracefully handle (the way Python 2.4 and earlier did) the case of # being called with no type or value (None, None, None). if (exc_value and getattr(exc_value, '__cause__', None) is not None and exc_value.__cause__ not in _seen): cause = TracebackException( type(exc_value.__cause__), exc_value.__cause__, exc_value.__cause__.__traceback__, limit=limit, lookup_lines=False, capture_locals=capture_locals, _seen=_seen) else: cause = None if (exc_value and getattr(exc_value, '__context__', None) is not None and exc_value.__context__ not in _seen): context = TracebackException( type(exc_value.__context__), exc_value.__context__, exc_value.__context__.__traceback__, limit=limit, lookup_lines=False, capture_locals=capture_locals, _seen=_seen) else: context = None self.__cause__ = cause self.__context__ = context self.__suppress_context__ = \ getattr(exc_value, '__suppress_context__', False) if exc_value else False # TODO: locals. self.stack = StackSummary.extract( walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines, capture_locals=capture_locals) self.exc_type = exc_type # Capture now to permit freeing resources: only complication is in the # unofficial API _format_final_exc_line self._str = _some_str(exc_value) if exc_type and issubclass(exc_type, SyntaxError): # Handle SyntaxError's specially self.filename = exc_value.filename self.lineno = str(exc_value.lineno) self.text = exc_value.text self.offset = exc_value.offset self.msg = exc_value.msg if lookup_lines: self._load_lines()
(self, exc_type, exc_value, exc_traceback, limit=None, lookup_lines=True, capture_locals=False, _seen=None)
18,560
traceback2
__str__
null
def __str__(self): return self._str
(self)
18,561
traceback2
_load_lines
Private API. force all lines in the stack to be loaded.
def _load_lines(self): """Private API. force all lines in the stack to be loaded.""" for frame in self.stack: frame.line if self.__context__: self.__context__._load_lines() if self.__cause__: self.__cause__._load_lines()
(self)
18,562
traceback2
format
Format the exception. If chain is not *True*, *__cause__* and *__context__* will not be formatted. The return value is a generator of strings, each ending in a newline and some containing internal newlines. `print_exception` is a wrapper around this method which just prints the lines to a file. The message indicating which exception occurred is always the last string in the output.
def format(self, chain=True): """Format the exception. If chain is not *True*, *__cause__* and *__context__* will not be formatted. The return value is a generator of strings, each ending in a newline and some containing internal newlines. `print_exception` is a wrapper around this method which just prints the lines to a file. The message indicating which exception occurred is always the last string in the output. """ if chain: if self.__cause__ is not None: for line in self.__cause__.format(chain=chain): yield line yield _cause_message elif (self.__context__ is not None and not self.__suppress_context__): for line in self.__context__.format(chain=chain): yield line yield _context_message yield u('Traceback (most recent call last):\n') for line in self.stack.format(): yield line for line in self.format_exception_only(): yield line
(self, chain=True)
18,563
traceback2
format_exception_only
Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emites several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output.
def format_exception_only(self): """Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emites several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. """ if self.exc_type is None: yield _format_final_exc_line(None, self._str) return stype = getattr(self.exc_type, '__qualname__', self.exc_type.__name__) smod = u(self.exc_type.__module__) if smod not in ("__main__", "builtins", "exceptions"): stype = smod + u('.') + stype if not issubclass(self.exc_type, SyntaxError): yield _format_final_exc_line(stype, self._str) return # It was a syntax error; show exactly where the problem was found. filename = _some_fs_str(self.filename) or u("<string>") lineno = str(self.lineno) or u('?') yield u(' File "{0}", line {1}\n').format(filename, lineno) badline = None if self.text is not None: if type(self.text) is bytes: # Not decoded - get the line via linecache which will decode # for us. if self.lineno: badline = linecache.getline(filename, int(lineno)) if not badline: # But we can't for some reason, so fallback to attempting a # u cast. badline = u(self.text) else: badline = self.text offset = self.offset if badline is not None: yield u(' {0}\n').format(badline.strip()) if offset is not None: caretspace = badline.rstrip('\n') offset = min(len(caretspace), offset) - 1 caretspace = caretspace[:offset].lstrip() # non-space whitespace (likes tabs) must be kept for alignment caretspace = ((c.isspace() and c or ' ') for c in caretspace) yield u(' {0}^\n').format(''.join(caretspace)) msg = self.msg or u("<no detail available>") yield u("{0}: {1}\n").format(stype, msg)
(self)
18,564
traceback2
_format_final_exc_line
null
def _format_final_exc_line(etype, value): valuestr = _some_str(value) if value == 'None' or value is None or not valuestr: line = u("%s\n") % etype else: line = u("%s: %s\n") % (etype, valuestr) return line
(etype, value)
18,565
traceback2
<lambda>
null
_identity = lambda:None
()
18,566
traceback2
_some_fs_str
_some_str, but for filesystem paths.
def _some_fs_str(value): """_some_str, but for filesystem paths.""" if value is None: return None try: if type(value) is bytes: return value.decode(sys.getfilesystemencoding()) except: pass return _some_str(value)
(value)
18,567
traceback2
_some_str
null
def _some_str(value): try: if PY2: # If there is a working __unicode__, great. # Otherwise see if we can get a bytestring... # Otherwise we fallback to unprintable. try: return unicode(value) except: return "b%s" % repr(str(value)) else: # For Python3, bytestrings don't implicit decode, so its trivial. return str(value) except: return '<unprintable %s object>' % type(value).__name__
(value)
18,568
traceback2
clear_frames
Clear all references to local variables in the frames of a traceback.
def clear_frames(tb): "Clear all references to local variables in the frames of a traceback." while tb is not None: try: getattr(tb.tb_frame, 'clear', _identity)() except RuntimeError: # Ignore the exception raised if the frame is still executing. pass tb = tb.tb_next
(tb)
18,569
traceback2
extract_stack
Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional 'f' and 'limit' arguments have the same meaning as for print_stack(). Each item in the list is a quadruple (filename, line number, function name, text), and the entries are in order from oldest to newest stack frame.
def extract_stack(f=None, limit=None): """Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional 'f' and 'limit' arguments have the same meaning as for print_stack(). Each item in the list is a quadruple (filename, line number, function name, text), and the entries are in order from oldest to newest stack frame. """ stack = StackSummary.extract(walk_stack(f), limit=limit) stack.reverse() return stack
(f=None, limit=None)