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. BASE_FILE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'uploads')
  21. class FileManager(models.Manager):
  22. def getHistory(self, user):
  23. # try:
  24. files = user.own_files.filter(usage="input").all()
  25. history = []
  26. for file in files:
  27. fileId = file.id
  28. directory = os.path.join(BASE_FILE_PATH, str(user.id))
  29. path = os.path.join(directory, str(fileId))
  30. try:
  31. size = os.path.getsize(path)
  32. except FileNotFoundError:
  33. print("未找到对应文件,现将记录删除1", fileId, file.name)
  34. self.get(id=fileId).delete()
  35. continue
  36. except Exception as error:
  37. print("读取历史记录时出现未知错误")
  38. return FAILED
  39. if size >= 1024 * 1024:
  40. size = size / (1024 * 1024)
  41. size = f"{size:.2f} MB"
  42. else:
  43. size = size / 1024
  44. size = f"{size:.2f} KB"
  45. history.append({
  46. 'id': file.id,
  47. 'name': file.name,
  48. 'uploadTime': file.update_time,
  49. 'size': size,
  50. 'content': file.content,
  51. })
  52. return history
  53. # except Exception as error:
  54. # print("Failed to get upload history", error)
  55. # return FAILED
  56. # Create your models here.
  57. class File(models.Model):
  58. name = models.CharField(default="untitled", max_length=64)
  59. type = models.CharField(choices=types, max_length=5)
  60. usage = models.CharField(choices=usages, max_length=20)
  61. create_time = models.DateTimeField(auto_now_add=True)
  62. update_time = models.DateTimeField(auto_now=True)
  63. content = models.CharField(choices=contents, max_length=10)
  64. associate = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True)
  65. user = models.ForeignKey(to="api.User", on_delete=models.CASCADE, related_name='own_files')
  66. objects = FileManager()
  67. def saveWithInfo(self):
  68. path = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.id))
  69. path2 = os.path.join(os.path.join(BASE_FILE_PATH, str(self.user.id)), str(self.associate.id))
  70. if self.content == 'node':
  71. sCount = dCount = iCount = 0
  72. nodeFile = csv.reader(open(path, 'r'))
  73. for line in nodeFile:
  74. if line[1] == 'S':
  75. sCount += 1
  76. if line[1] == 'D':
  77. dCount += 1
  78. if line[1] == 'I':
  79. iCount += 1
  80. fileInfo = FileInfo()
  81. fileInfo.file = self
  82. fileInfo.nodes = sCount + dCount + iCount
  83. fileInfo.sNodes = sCount
  84. fileInfo.dNodes = dCount
  85. fileInfo.iNodes = iCount
  86. fileInfo.save()
  87. if self.content == 'edge':
  88. edges = 0
  89. edgeFile = csv.reader(open(path2, 'r'))
  90. for line in edgeFile:
  91. edges += 1
  92. fileInfo = FileInfo()
  93. fileInfo.file = self
  94. fileInfo.edges = edges
  95. fileInfo.save()
  96. self.save()
  97. def generate(self, data):
  98. # 从json结果生成文件
  99. path = os.path.join(BASE_FILE_PATH, str(self.user.id))
  100. if os.path.exists(os.path.join(path, str(self.id))):
  101. self.delete()
  102. return FILE_ALREADY_EXIST
  103. else:
  104. if self.content == 'node':
  105. nodes = []
  106. file = open(os.path.join(path, str(self.id)), 'w', newline='')
  107. csvFile = csv.writer(file)
  108. for line in data:
  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. # 除了节点编号和节点类型外,其余参数全部放在line的后续位置,以字符串json的格式保存
  121. csvFile.writerow(line)
  122. file.close()
  123. return OK
  124. if self.content == 'edge':
  125. edges = []
  126. file = open(os.path.join(path, str(self.id)), 'w', newline='')
  127. csvFile = csv.writer(file)
  128. for line in data:
  129. if not str(line[0]).isdigit() or not str(line[1]).isdigit():
  130. print("check file illegal failed", "edge", "len =2")
  131. return FAILED
  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", "len = 2")
  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'