file.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. from django.db import models
  2. import os, errno
  3. import csv
  4. from api.utils import *
  5. types = [
  6. ('csv', 'csv'),
  7. ]
  8. usages = [
  9. ('input', 'input'),
  10. ('show', 'show'),
  11. ('result', 'result'),
  12. ('output', 'output'),
  13. ]
  14. contents = [
  15. ('node', 'node'),
  16. ('edge', 'edge'),
  17. ]
  18. BASE_FILE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'uploads')
  19. class FileManager(models.Manager):
  20. def getHistory(self, user):
  21. # try:
  22. files = user.own_files.all()
  23. history = []
  24. for file in files:
  25. fileId = file.id
  26. directory = os.path.join(BASE_FILE_PATH, str(user.id))
  27. path = os.path.join(directory, str(fileId))
  28. try:
  29. size = os.path.getsize(path)
  30. except FileNotFoundError:
  31. print("未找到对应文件,现将记录删除1", fileId, file.name)
  32. self.get(id=fileId).delete()
  33. continue
  34. except Exception as error:
  35. print("读取历史记录时出现未知错误")
  36. return FAILED
  37. if size >= 1024 * 1024:
  38. size = size / (1024 * 1024)
  39. size = f"{size:.2f} MB"
  40. else:
  41. size = size / 1024
  42. size = f"{size:.2f} KB"
  43. history.append({
  44. 'id': file.id,
  45. 'name': file.name,
  46. 'uploadTime': file.update_time,
  47. 'size': size,
  48. 'content': file.content,
  49. })
  50. return history
  51. # except Exception as error:
  52. # print("Failed to get upload history", error)
  53. # return FAILED
  54. # Create your models here.
  55. class File(models.Model):
  56. name = models.CharField(default="untitled", max_length=64)
  57. type = models.CharField(choices=types, max_length=5)
  58. usage = models.CharField(choices=usages, max_length=20)
  59. create_time = models.DateTimeField(auto_now_add=True)
  60. update_time = models.DateTimeField(auto_now=True)
  61. content = models.CharField(choices=contents, max_length=10)
  62. associate = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True)
  63. user = models.ForeignKey(to="api.User", on_delete=models.CASCADE, related_name='own_files')
  64. objects = FileManager()
  65. def saveWithInfo(self):
  66. path = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.id))
  67. path2 = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.associate.id))
  68. if self.content == 'node':
  69. sCount = dCount = iCount = 0
  70. nodeFile = csv.reader(open(path, 'r'))
  71. for line in nodeFile:
  72. if line[1] == 'S':
  73. sCount += 1
  74. if line[1] == 'D':
  75. dCount += 1
  76. if line[1] == 'I':
  77. iCount += 1
  78. fileInfo = FileInfo()
  79. fileInfo.file = self
  80. fileInfo.nodes = sCount + dCount + iCount
  81. fileInfo.sNodes = sCount
  82. fileInfo.dNodes = dCount
  83. fileInfo.iNodes = iCount
  84. fileInfo.save()
  85. if self.content == 'edge':
  86. edges = 0
  87. edgeFile = csv.reader(open(path2, 'r'))
  88. for line in edgeFile:
  89. edges += 1
  90. fileInfo = FileInfo()
  91. fileInfo.file = self
  92. fileInfo.edges = edges
  93. fileInfo.save()
  94. self.save()
  95. def generate(self, data):
  96. path = os.path.join(BASE_FILE_PATH, str(self.user.id))
  97. if os.path.exists(os.path.join(path, str(self.id))):
  98. self.delete()
  99. return FILE_ALREADY_EXIST
  100. else:
  101. if self.content == 'node':
  102. nodes = []
  103. file = open(os.path.join(path, str(self.id)), 'w', newline='')
  104. csvFile = csv.writer(file)
  105. for line in data:
  106. if not len(line) == 2:
  107. print("check file illegal failed", "node", "len = 2")
  108. return FAILED
  109. if not str(line[0]).isdigit():
  110. print("check file illegal failed", "node", "id wrong")
  111. return FAILED
  112. if not line[1] in ['S', 'D', 'I']:
  113. print("check file illegal failed", "node", "type wrong")
  114. return FAILED
  115. if line[0] not in nodes:
  116. nodes.append(line[0])
  117. else:
  118. print("check file illegal failed", "node", "dudplicate id")
  119. return FAILED
  120. csvFile.writerow(line)
  121. file.close()
  122. return OK
  123. if self.content == 'edge':
  124. edges = []
  125. file = open(os.path.join(path, str(self.id)), 'w', newline='')
  126. csvFile = csv.writer(file)
  127. for line in data:
  128. if not len(line) == 2:
  129. print("check file illegal failed", "edge", "len =2")
  130. return FAILED
  131. if [line[0], line[1]] not in edges and [line[1], line[0]] not in edges:
  132. edges.append([line[0], line[1]])
  133. csvFile.writerow(line)
  134. file.close()
  135. return OK
  136. return UNKNOWN_CONTENT
  137. def storage(self, file):
  138. try:
  139. path = os.path.join(BASE_FILE_PATH, str(self.user.id))
  140. if os.path.exists(os.path.join(path, str(self.id))):
  141. self.delete()
  142. return FILE_ALREADY_EXIST
  143. else:
  144. try:
  145. os.mkdir(path)
  146. except Exception as error:
  147. if not error.args[0] == 17:
  148. print(error)
  149. return FILE_FAILED_CREATE_DIR
  150. file_path = os.path.join(path, str(self.id))
  151. f = open(file_path, 'wb')
  152. for bite in file:
  153. f.write(bite)
  154. f.close()
  155. return OK
  156. except Exception as error:
  157. print(error)
  158. return FAILED
  159. # 检查文件是否合法
  160. def checkIllegal(self):
  161. path = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.id))
  162. path2 = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.associate.id))
  163. if self.content == 'node':
  164. file = csv.reader(open(path, 'r'))
  165. # 针对csv文件的检测
  166. if self.type == 'csv':
  167. nodes = []
  168. for line in file:
  169. if not len(line) == 2:
  170. print("check file illegal failed", "node", "len = 2")
  171. return False
  172. if not line[0].isdigit():
  173. print("check file illegal failed", "node", "id wrong")
  174. return False
  175. if not line[1] in ['S', 'D', 'I']:
  176. print("check file illegal failed", "node", "type wrong")
  177. return False
  178. if line[0] not in nodes:
  179. nodes.append(line[0])
  180. else:
  181. print("check file illegal failed", "node", "dudplicate id")
  182. return False
  183. return True
  184. if self.content == 'edge':
  185. edgeFile = csv.reader(open(path, 'r'))
  186. nodeFile = csv.reader(open(path2, 'r'))
  187. # 针对csv文件的检测
  188. if self.type == 'csv':
  189. nodes = []
  190. edges = []
  191. for line in nodeFile:
  192. if not len(line) == 2:
  193. print("check file illegal failed", "node", "len = 2")
  194. return False
  195. if not line[0].isdigit():
  196. print("check file illegal failed", "node", "len = 2")
  197. return False
  198. nodes.append(line[0])
  199. for line in edgeFile:
  200. if not len(line) == 2:
  201. print("check file illegal failed", "edge", "len =2")
  202. return False
  203. if line[0] not in nodes or line[1] not in nodes:
  204. print("check file illegal failed", "edge", "id not exist")
  205. return False
  206. if [line[0], line[1]] not in edges and [line[1], line[0]] not in edges:
  207. edges.append([line[0], line[1]])
  208. else:
  209. # 将图视为无向图,同一条边的正反算作重复
  210. print("check file illegal failed", "edge", "duplicate edge")
  211. return False
  212. return True
  213. def toJson(self):
  214. path = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.id))
  215. file = csv.reader(open(path, 'r'))
  216. if self.content == 'node':
  217. if self.type == 'csv':
  218. nodes = []
  219. for line in file:
  220. nodes.append({'id': line[0], 'type': line[1]})
  221. return nodes
  222. if self.content == 'edge':
  223. if self.type == 'csv':
  224. edges = []
  225. for line in file:
  226. edges.append([line[0], line[1]])
  227. return edges
  228. def deleteStorage(self):
  229. path = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.id))
  230. if self.associate:
  231. path2 = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.associate.id))
  232. else:
  233. path2 = ""
  234. failedFlag = False
  235. for p in [path, path2]:
  236. if os.path.exists(p):
  237. try:
  238. os.remove(p)
  239. except Exception as error:
  240. # 可能出现失败的原因是文件被占用
  241. print("删除文件" + self.id + self.name + "失败", error)
  242. failedFlag = True
  243. # 无论文件删除是否成功,都要把记录删除,多余的文件可以再后续清理时删除
  244. if self.associate:
  245. self.associate.delete()
  246. if self:
  247. self.delete()
  248. if failedFlag:
  249. return FAILED
  250. return OK
  251. class Meta:
  252. app_label = 'api'
  253. class FileInfo(models.Model):
  254. file = models.OneToOneField(File, on_delete=models.CASCADE, related_name='own_file_info')
  255. nodes = models.IntegerField(default=0)
  256. sNodes = models.IntegerField(default=0)
  257. dNodes = models.IntegerField(default=0)
  258. iNodes = models.IntegerField(default=0)
  259. edges = models.IntegerField(default=0)
  260. # 待添加集中度等边的信息
  261. class Meta:
  262. app_label = 'api'