File size: 1,663 Bytes
661ec13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60


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
            #print(f"ctime={ctime},current_time={current_time},passed_time={passed_time},diff={diff}")
            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