63 lines
1.4 KiB
Python
63 lines
1.4 KiB
Python
|
|
||
|
import os
|
||
|
import typing
|
||
|
import uuid
|
||
|
|
||
|
TEXTCHARS = bytearray({7, 8, 9, 10, 12, 13, 27} |
|
||
|
set(range(0x20, 0x100)) - {0x7f})
|
||
|
|
||
|
|
||
|
def delete_root_slash(path: str) -> str:
|
||
|
if path.startswith('/'):
|
||
|
path = path[1:]
|
||
|
return path
|
||
|
|
||
|
|
||
|
def add_fast_api_root(path):
|
||
|
fast_api_root = os.environ.get('FASTAPI_ROOT_URL')
|
||
|
if path.startswith(fast_api_root):
|
||
|
return path
|
||
|
return os.path.join(os.environ.get('FASTAPI_ROOT_URL'), delete_root_slash(path))
|
||
|
|
||
|
def remove_fastapi_root(path):
|
||
|
return path.replace(os.environ.get('FASTAPI_ROOT_URL'), "")
|
||
|
|
||
|
def is_binary_file(file_path: str):
|
||
|
with open(file_path, 'rb') as f:
|
||
|
content = f.read(1024)
|
||
|
return bool(content.translate(None, TEXTCHARS))
|
||
|
|
||
|
|
||
|
def get_or_create_dir(path: str) -> str:
|
||
|
if not os.path.exists(path):
|
||
|
os.mkdir(path)
|
||
|
return path
|
||
|
|
||
|
|
||
|
def get_filename(file: typing.IO, default: str = uuid.uuid4()) -> str:
|
||
|
if hasattr(file, 'name'):
|
||
|
return file.name
|
||
|
elif hasattr(file, 'filename'):
|
||
|
return file.filename
|
||
|
else:
|
||
|
return f"{default}.py"
|
||
|
|
||
|
|
||
|
def remove_if_exists(path):
|
||
|
if os.path.exists(path) and os.path.isfile(path):
|
||
|
os.remove(path)
|
||
|
|
||
|
|
||
|
def get_parent_dir(path):
|
||
|
return os.path.abspath(os.path.join(path, os.pardir))
|
||
|
|
||
|
|
||
|
def get_ancestor(path: str, levels: int = 1):
|
||
|
for i in range(levels):
|
||
|
path = get_parent_dir(path)
|
||
|
return path
|
||
|
|
||
|
|
||
|
def get_filename_from_path(path):
|
||
|
return os.path.split(path)[-1]
|