__init__.py 1.18 KB
Newer Older
Wei Shoulin's avatar
Wei Shoulin committed
1
from .version import __version__
Wei Shoulin's avatar
Wei Shoulin committed
2
from .common import request
Wei Shoulin's avatar
Wei Shoulin committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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。
    """
Wei Shoulin's avatar
Wei Shoulin committed
23
    response = request.download_file(f"/api/common/download/file?file_path={file_path}")
Wei Shoulin's avatar
Wei Shoulin committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    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。
    """
Wei Shoulin's avatar
Wei Shoulin committed
41
    from .common import fs
Wei Shoulin's avatar
Wei Shoulin committed
42
43
44
45
46
47
    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