-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
35 lines (29 loc) · 1.06 KB
/
utils.py
File metadata and controls
35 lines (29 loc) · 1.06 KB
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
"""通用的工具函式"""
import os
import hashlib
from pathlib import Path
ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'docx', 'pptx', 'zip', 'md', 'markdown'}
def allowed_file(filename):
"""檢查檔案副檔名是否允許"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def get_file_extension(filename):
"""獲取檔案副檔名"""
if '.' in filename:
return filename.rsplit('.', 1)[1].lower()
return ''
def calculate_file_hash(file_path):
"""計算檔案的 SHA256 雜湊值"""
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
# 讀取區塊以處理大型檔案
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def ensure_upload_dir(directory):
"""確保上傳目錄存在"""
if not os.path.exists(directory):
os.makedirs(directory)
def get_file_size(file_path):
"""獲取檔案大小(字節)"""
return os.path.getsize(file_path)