-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles.py
61 lines (49 loc) · 2.35 KB
/
files.py
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
61
def save_images(files, upload_folder, db_insert_function):
"""
دالة عامة لرفع صورة أو عدة صور وإرجاع المفتاح الرئيسي لكل سجل.
Args:
files (list): قائمة بملفات الصور.
upload_folder (str): مسار المجلد الذي سيتم حفظ الصور فيه.
db_insert_function (function): دالة لإضافة البيانات إلى قاعدة البيانات.
Returns:
dict: يحتوي على قائمة الصور التي تم رفعها مع المفاتيح الرئيسية أو الأخطاء.
"""
# التأكد من أن المجلد موجود
if not os.path.exists(upload_folder):
os.makedirs(upload_folder)
# السماح بامتدادات معينة فقط
allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions
uploaded_files = []
errors = []
for file in files:
if file and allowed_file(file.filename):
filename = file.filename
filepath = os.path.join(upload_folder, filename)
try:
# حفظ الملف في المجلد
file.save(filepath)
# تجهيز البيانات للإدخال في قاعدة البيانات
data = {
'img_name': filename,
'img_path': filepath
}
# استدعاء دالة الإدخال والحصول على المفتاح الرئيسي
record_id = db_insert_function('images', data)
if record_id is not None:
uploaded_files.append({
'img_name': filename,
'img_path': filepath,
'img_id': record_id
})
else:
errors.append(f"Failed to save {filename} in database.")
except Exception as e:
errors.append(f"Failed to upload {filename}: {str(e)}")
else:
errors.append(f"Invalid file: {file.filename if file else 'Unknown'}")
return {
"uploaded_files": uploaded_files,
"errors": errors
}