__init__.py 1.16 KB
Newer Older
Wei Shoulin's avatar
Wei Shoulin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from .version import __version__
from .common import request, fs
from io import BytesIO
from .exceptions.exception import AppError
__all__ = [
    "__version__",
    "download_file",
    "read_file",
]
def download_file(file_path: str) -> bytes:
    """
    下载文件。
    
    Args:
        file_path (str): 相对文件路径。
    
    Returns:
        bytes: 文件内容。
    
    Raises:
        Exception: 如果下载失败,则抛出异常AppError。
    """
    response = request.download_file(f"/common/download/file?file_path={file_path}")
    if not response.ok:
        raise AppError("Failed to download the file. Reason: " + response.reason)
    return response.content

def read_file(file_path: str) -> BytesIO:
    """
    读取文件。
    
    Args:
        file_path (str): 相对文件路径。
    
    Returns:
        BytesIO: 文件内容。
    
    Raises:
        Exception: 如果读取失败,则抛出异常AppError。
    """
    with fs.get_file_storage().read_file(file_path) as iobytes_io:
        try:
            iobytes_io.seek(0)
        except OSError:
            raise AppError("Failed to read file.")
        return iobytes_io