file.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 in ['node', 'nodes']:
  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 in ['edge', 'edges']:
  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. # 检查重复
  133. if [line[0], line[1]] not in edges and [line[1], line[0]] not in edges:
  134. edges.append([line[0], line[1]])
  135. # 后续参数放在line的后续位置
  136. csvFile.writerow(line)
  137. file.close()
  138. return OK
  139. return UNKNOWN_CONTENT
  140. def storage(self, file):
  141. try:
  142. path = os.path.join(BASE_FILE_PATH, str(self.user.id))
  143. if os.path.exists(os.path.join(path, str(self.id))):
  144. self.delete()
  145. return FILE_ALREADY_EXIST
  146. else:
  147. try:
  148. os.mkdir(path)
  149. except Exception as error:
  150. if not error.args[0] == 17:
  151. print(error)
  152. return FILE_FAILED_CREATE_DIR
  153. file_path = os.path.join(path, str(self.id))
  154. f = open(file_path, 'wb')
  155. for bite in file:
  156. f.write(bite)
  157. f.close()
  158. return OK
  159. except Exception as error:
  160. print(error)
  161. return FAILED
  162. # 检查文件是否合法
  163. def checkIllegal(self):
  164. path = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.id))
  165. path2 = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.associate.id))
  166. if self.content == 'node':
  167. file = csv.reader(open(path, 'r'))
  168. # 针对csv文件的检测
  169. if self.type == 'csv':
  170. nodes = []
  171. for line in file:
  172. if not len(line) >= 2:
  173. print("check file illegal failed", "node", "len >= 2")
  174. return False
  175. if not line[0].isdigit():
  176. print("check file illegal failed", "node", "id wrong")
  177. return False
  178. if not line[1] in ['S', 'D', 'I']:
  179. print("check file illegal failed", "node", "type wrong")
  180. return False
  181. if line[0] not in nodes:
  182. nodes.append(line[0])
  183. else:
  184. print("check file illegal failed", "node", "dudplicate id")
  185. return False
  186. return True
  187. if self.content == 'edge':
  188. edgeFile = csv.reader(open(path, 'r'))
  189. nodeFile = csv.reader(open(path2, 'r'))
  190. # 针对csv文件的检测
  191. if self.type == 'csv':
  192. nodes = []
  193. edges = []
  194. for line in nodeFile:
  195. if not len(line) >= 2:
  196. print("check file illegal failed", "node", "len >= 2")
  197. return False
  198. if not line[0].isdigit():
  199. print("check file illegal failed", "node", "id wrong")
  200. return False
  201. nodes.append(line[0])
  202. for line in edgeFile:
  203. if not len(line) == 2:
  204. print("check file illegal failed", "edge", "len =2")
  205. return False
  206. if line[0] not in nodes or line[1] not in nodes:
  207. print("check file illegal failed", "edge", "id not exist")
  208. return False
  209. if [line[0], line[1]] not in edges and [line[1], line[0]] not in edges:
  210. edges.append([line[0], line[1]])
  211. else:
  212. # 将图视为无向图,同一条边的正反算作重复
  213. print("check file illegal failed", "edge", "duplicate edge")
  214. return False
  215. return True
  216. def toJson(self):
  217. path = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.id))
  218. file = csv.reader(open(path, 'r'))
  219. if self.content == 'node':
  220. if self.type == 'csv':
  221. nodes = []
  222. for line in file:
  223. # 如果有额外数据,则放入第三个字段中
  224. node = {'id': line[0], 'type': line[1], 'meta': []}
  225. for el in range(2, len(line)):
  226. node['meta'].append(json.loads(el))
  227. # 测试用,添加optimize
  228. el = '{"optimize": "old"}'
  229. node['meta'].append(json.loads(el))
  230. # 测试用,添加group
  231. el = '{"group": "' + str(randint(1,5)) + '"}'
  232. node['meta'].append(json.loads(el))
  233. nodes.append(node)
  234. return nodes
  235. if self.content == 'edge':
  236. if self.type == 'csv':
  237. edges = []
  238. for line in file:
  239. # 如果有额外数据,则放入第三个字段中
  240. edge = {'from': line[0], 'to': line[1], 'meta': []}
  241. for el in range(2, len(line)):
  242. edge['meta'].append(json.loads(el))
  243. # 测试用,添加optimize
  244. el = '{"optimize": "old"}'
  245. edge['meta'].append(json.loads(el))
  246. edges.append(edge)
  247. return edges
  248. def deleteStorage(self):
  249. path = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.id))
  250. if self.associate:
  251. path2 = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.associate.id))
  252. else:
  253. path2 = ""
  254. failedFlag = False
  255. for p in [path, path2]:
  256. if os.path.exists(p):
  257. try:
  258. os.remove(p)
  259. except Exception as error:
  260. # 可能出现失败的原因是文件被占用
  261. print("删除文件" + self.id + self.name + "失败", error)
  262. failedFlag = True
  263. # 无论文件删除是否成功,都要把记录删除,多余的文件可以再后续清理时删除
  264. if self.associate:
  265. self.associate.delete()
  266. if self:
  267. self.delete()
  268. if failedFlag:
  269. return FAILED
  270. return OK
  271. class Meta:
  272. app_label = 'api'
  273. class FileInfo(models.Model):
  274. file = models.OneToOneField(File, on_delete=models.CASCADE, related_name='own_file_info')
  275. nodes = models.IntegerField(default=0)
  276. sNodes = models.IntegerField(default=0)
  277. dNodes = models.IntegerField(default=0)
  278. iNodes = models.IntegerField(default=0)
  279. edges = models.IntegerField(default=0)
  280. # 待添加集中度等边的信息
  281. class Meta:
  282. app_label = 'api'