yekkala commited on
Commit
c1a7abf
·
verified ·
1 Parent(s): b633831

Create file_handler.py

Browse files
Files changed (1) hide show
  1. utils/file_handler.py +62 -0
utils/file_handler.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File handling utilities for SkillSync
3
+ """
4
+
5
+ import os
6
+ import shutil
7
+ from datetime import datetime
8
+
9
+ class FileHandler:
10
+ """Handles file operations for submissions"""
11
+
12
+ def __init__(self, upload_dir="data/user_data/submissions", max_size_mb=100):
13
+ self.upload_dir = upload_dir
14
+ self.max_size = max_size_mb * 1024 * 1024
15
+ self.allowed_extensions = [".zip", ".pdf", ".ipynb", ".py", ".txt", ".md"]
16
+
17
+ def ensure_upload_dir(self):
18
+ """Ensure upload directory exists"""
19
+ os.makedirs(self.upload_dir, exist_ok=True)
20
+
21
+ def validate_file(self, file):
22
+ """Validate uploaded file"""
23
+ if file is None:
24
+ return False, "No file provided"
25
+
26
+ file_name = getattr(file, 'name', 'unknown')
27
+ file_ext = os.path.splitext(file_name)[1].lower()
28
+
29
+ if file_ext not in self.allowed_extensions:
30
+ return False, f"File type {file_ext} not allowed"
31
+
32
+ return True, "File validated successfully"
33
+
34
+ def save_file(self, file, user_id, assignment_type):
35
+ """Save uploaded file"""
36
+ try:
37
+ self.ensure_upload_dir()
38
+ original_name = getattr(file, 'name', 'uploaded_file')
39
+ original_name = os.path.basename(original_name)
40
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
41
+ new_name = f"{user_id}_{assignment_type}_{timestamp}_{original_name}"
42
+ destination = os.path.join(self.upload_dir, new_name)
43
+
44
+ if hasattr(file, 'name'):
45
+ shutil.copy2(file.name, destination)
46
+
47
+ return True, destination
48
+ except Exception as e:
49
+ return False, str(e)
50
+
51
+ def get_file_info(self, filepath):
52
+ """Get information about a file"""
53
+ if not os.path.exists(filepath):
54
+ return None
55
+
56
+ stat = os.stat(filepath)
57
+ return {
58
+ "path": filepath,
59
+ "size": stat.st_size,
60
+ "created": datetime.fromtimestamp(stat.st_ctime).strftime("%Y-%m-%d %H:%M:%S"),
61
+ "modified": datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M:%S")
62
+ }