file.py 12 KB

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