|
|
|
|
|
import os |
|
import time |
|
import io |
|
import hashlib |
|
|
|
def clear_old_files(dir="files",passed_time=60*60): |
|
try: |
|
files = os.listdir(dir) |
|
current_time = time.time() |
|
for file in files: |
|
file_path = os.path.join(dir,file) |
|
|
|
ctime = os.stat(file_path).st_ctime |
|
diff = current_time - ctime |
|
|
|
if diff > passed_time: |
|
os.remove(file_path) |
|
except: |
|
print("maybe still gallery using error") |
|
|
|
def get_buffer_id(buffer): |
|
hash_object = hashlib.sha256(buffer.getvalue()) |
|
hex_dig = hash_object.hexdigest() |
|
unique_id = hex_dig[:32] |
|
return unique_id |
|
|
|
def get_image_id(image): |
|
buffer = io.BytesIO() |
|
image.save(buffer, format='PNG') |
|
return get_buffer_id(buffer) |
|
|
|
def save_image(image,extension="jpg",dir_name="files"): |
|
id = get_image_id(image) |
|
os.makedirs(dir_name,exist_ok=True) |
|
file_path = f"{dir_name}/{id}.{extension}" |
|
|
|
image.save(file_path) |
|
return file_path |
|
|
|
def save_buffer(buffer,extension="webp",dir_name="files"): |
|
id = get_buffer_id(buffer) |
|
os.makedirs(dir_name,exist_ok=True) |
|
file_path = f"{dir_name}/{id}.{extension}" |
|
|
|
with open(file_path,"wb") as f: |
|
f.write(buffer.getvalue()) |
|
return file_path |
|
|
|
def write_file(file_path,text): |
|
with open(file_path, 'w', encoding='utf-8') as f: |
|
f.write(text) |
|
|
|
def read_file(file_path): |
|
"""read the text of target file |
|
""" |
|
with open(file_path, 'r', encoding='utf-8') as f: |
|
content = f.read() |
|
return content |