file.py 12 KB

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