setup_db.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. # -*- coding: UTF-8 -*-
  2. import requests
  3. import sys
  4. import json
  5. import random
  6. import string
  7. import os
  8. from csv import reader
  9. from datetime import datetime
  10. from user_test import get_user, get_all_users, delete_user
  11. from group_test import get_group_by_name, get_group, create_group, add_user_to_group
  12. from exam_test import create_exam, create_question, get_question, add_question_to_exam
  13. from category_test import create_material, get_material, create_category, get_category, add_material_to_category, update_category, create_question_category, get_question_category, questions_in_category, add_question_to_question_category, update_question_category, show_root_categories
  14. from learningmaterial_test import add_comment
  15. USERNAME_RANDOM_LENGTH = 10
  16. from constants import WEBSITE_PREFIX
  17. override = False
  18. want_material = False
  19. want_user = False
  20. want_question = False
  21. if len(sys.argv) > 1:
  22. for arg in sys.argv:
  23. if arg == 'override':
  24. override = True
  25. if arg == 'material':
  26. want_material = True
  27. if arg == 'user':
  28. want_user = True
  29. if arg == 'question':
  30. want_question = True
  31. def _random_string(length):
  32. letters = string.ascii_letters
  33. return ''.join(random.choice(letters) for i in range(length))
  34. def _text(resp):
  35. return json.loads(resp.text)
  36. # 创建 10 个 前缀为namePrefix 密码为password的 用户
  37. def add_dummy_users(namePrefix = 'testuser-', password = 'test', number = 10):
  38. groups = add_groups()
  39. users = []
  40. nicknames = ['小强', '小张', '小李', '大王']
  41. firstNames = ['一', '二', '三', '四', '五']
  42. lastNames = ['张', '王', '李', '杜', '靳']
  43. for i in range(number):
  44. user_name = namePrefix + _random_string(USERNAME_RANDOM_LENGTH)
  45. # register_user(user_name, password)
  46. new_user = {
  47. 'userName': user_name,
  48. 'password': password,
  49. 'nickName': nicknames[i % len(nicknames)],
  50. 'studyId': 'U0000' + str(i),
  51. 'email': 'test@gmail.com',
  52. 'firstName': firstNames[i % len(firstNames)],
  53. 'lastName': lastNames[i % len(lastNames)],
  54. 'phone': '13060901234',
  55. 'birthday': '1999-01-01',
  56. }
  57. register_user(new_user)
  58. user = get_user(user_name)
  59. random_group = groups[random.randint(0, len(groups)-1)]
  60. add_user_to_group(random_group, _text(user))
  61. users.append(_text(user)['userName'])
  62. print('created ' + str(len(users)) + ' users: ' + ','.join(users))
  63. global all_users
  64. all_users = users
  65. return users
  66. # 创建 3个二级的group
  67. # orgtest-level1
  68. # orgtest-level2-a orgtest-level2-b orgtest-level2-c
  69. def add_groups(namePrefix = 'orgtest-', number=3):
  70. # creating level1 group
  71. level1_name = namePrefix + 'level1-' + _random_string(3)
  72. level1_group_body = {
  73. 'name': level1_name
  74. }
  75. create_group(level1_group_body)
  76. level1_group = _text(get_group_by_name(level1_name))
  77. groups = []
  78. for i in range(number):
  79. level2_group_body = {
  80. 'name': namePrefix + 'level2-' + _random_string(3),
  81. 'parentGroupId': level1_group['id']
  82. }
  83. resp = create_group(level2_group_body)
  84. groupId = _text(resp)['id']
  85. groups.append(groupId)
  86. print ('created ' + str(len(groups)) + ' groups: ' + ','.join(groups))
  87. return groups
  88. def randomly_pick_user():
  89. global all_users
  90. rand_index = random.randint(0, len(all_users) - 1)
  91. return all_users[rand_index]
  92. def create_exams(namePrefix='测试考试-', number=2, tags=[]):
  93. exams = []
  94. for i in range(number):
  95. new_exam = {
  96. 'name': namePrefix + _random_string(3),
  97. 'description': '可以回家做',
  98. 'duration': random.randint(0, 863) * 100, # seconds
  99. 'tags': tags,
  100. 'startTime': '2021-05-01T10:00:00'
  101. }
  102. resp = create_exam(new_exam)
  103. exams.append(_text(resp)['id'])
  104. print ('created ' + str(len(exams)) + ' exams: ' + ','.join(exams))
  105. return exams
  106. def create_questions(namePrefix='qtest-', number=10, from_file=False):
  107. exams = []
  108. if not from_file:
  109. exams = create_exams()
  110. questions = []
  111. question_categories = create_question_categories()
  112. if from_file:
  113. files = os.listdir('./demo-questions/')
  114. for file_name in files:
  115. with open('./demo-questions/' + file_name, 'r') as read_obj:
  116. print('loading ' + file_name + ' to db')
  117. exam_tag = file_name.split('-')[1]
  118. tags = []
  119. if len(exam_tag) > 0:
  120. if exam_tag == '线路工':
  121. tags.append('XianLuGong')
  122. elif exam_tag == '桥隧工':
  123. tags.append('QiaoSuiGong')
  124. elif exam_tag == '大型线路机械司机':
  125. tags.append('DaXingXianLuJiXieSiJi')
  126. elif exam_tag == '测量工':
  127. tags.append('CeLiangGong')
  128. exam_prefix = file_name.split('-')[0]
  129. exams = create_exams(namePrefix=exam_prefix + '-' + exam_tag, number=6, tags=tags)
  130. csv_reader = reader(read_obj)
  131. for row in csv_reader:
  132. qNumber = row[0]
  133. if qNumber == '题号' or len(qNumber) < 1:
  134. continue
  135. content = row[1] # required
  136. temp_type = row[2] # required
  137. qType = 'DanXuan'
  138. if temp_type == '2':
  139. qType = 'DuoXuan'
  140. if temp_type == '3':
  141. qType = 'PanDuan'
  142. answers = [] # required
  143. for i in [3, 4, 5, 6]:
  144. if len(row[i]) > 0:
  145. answers.append(row[i])
  146. finalAnswer = row[7] # required
  147. answerAnalysis = row[8]
  148. keyword = row[9];
  149. level = row[10];
  150. if len(content) == 0 or len(qType) == 0 or len(answers) == 0 or len(finalAnswer) == 0:
  151. print('Skip due to required info missing')
  152. continue
  153. question = {
  154. 'userId': randomly_pick_user(),
  155. 'content': content,
  156. 'answers': answers,
  157. 'finalAnswer': [finalAnswer],
  158. 'keyword': keyword,
  159. 'type': qType,
  160. 'questionLevel': level,
  161. 'tags': tags,
  162. 'answerAnalysis': answerAnalysis,
  163. }
  164. resp = create_question(question)
  165. random_exam_id = exams[random.randint(0, len(exams)-1)]
  166. exam_to_question = {
  167. 'questionId': _text(resp)['id']
  168. }
  169. # if random number equals to magic number, then add tag 今日必练
  170. if random.randint(0, 100) == 3:
  171. print('going to add tag to question')
  172. add_tag(datetime.today().strftime('%Y%m%d'), questionId=_text(resp)['id'])
  173. # add newly created question to a random exam
  174. add_question_to_exam(random_exam_id, [exam_to_question])
  175. questions.append(_text(resp)['id'])
  176. else:
  177. for i in range(number):
  178. question = {
  179. 'userId': randomly_pick_user(),
  180. 'content': namePrefix + '天上什么星星最亮?-' + str(i),
  181. 'answers': ['太阳', '小天狼星', '北极星'],
  182. 'finalAnswer': ['小天狼星'],
  183. 'type': 'DanXuan' # 单选题
  184. }
  185. resp = create_question(question)
  186. random_exam_id = exams[random.randint(0, len(exams)-1)]
  187. # add newly created question to a random exam
  188. add_question_to_exam(random_exam_id, [_text(resp)])
  189. questions.append(_text(resp)['id'])
  190. tiankong_question = {
  191. 'userId': randomly_pick_user(),
  192. 'content': namePrefix + '天上$PH$最亮?-' + str(i),
  193. 'finalAnswer': ['小天狼星'],
  194. 'type': 'TianKong' # 填空题
  195. }
  196. resp = create_question(tiankong_question)
  197. random_exam_id = exams[random.randint(0, len(exams)-1)]
  198. # add newly created question to a random exam
  199. add_question_to_exam(random_exam_id, [_text(resp)])
  200. random_category_id = question_categories[random.randint(0, len(question_categories)-1)]
  201. add_question_to_question_category(random_category_id, _text(resp))
  202. questions.append(_text(resp)['id'])
  203. print ('created ' + str(len(questions)) + ' questions')
  204. return questions
  205. def create_question_categories(namePrefix= '知识类-', number=3):
  206. resp = create_question_category(namePrefix + _random_string(3))
  207. question_root_id = _text(resp)['id']
  208. categories = []
  209. names = ['科普类-', '技术类-', '历史类-', '天文类-', '兴趣类-']
  210. for i in range(number):
  211. child = create_question_category(names[i % len(names)] + _random_string(3))
  212. child_id = _text(child)['id']
  213. update_question_category(child_id, {
  214. 'parentId': question_root_id
  215. })
  216. categories.append(child_id)
  217. print ('created ' + str(len(categories)) + ' question categories: ' + ','.join(categories))
  218. return categories
  219. def create_categories(namePrefix= 'testCategory-', number=3):
  220. resp = create_category(namePrefix + 'root-' + _random_string(3))
  221. root_id = _text(resp)['id']
  222. categories = []
  223. for i in range(number):
  224. child = create_category(namePrefix + 'child-' + _random_string(3))
  225. child_id = _text(child)['id']
  226. update_category(child_id, {
  227. 'parentId': root_id
  228. })
  229. categories.append(child_id)
  230. print ('created ' + str(len(categories)) + ' categories: ' + ','.join(categories))
  231. return categories
  232. def create_2_levels_categories(root_level, second_levels):
  233. resp = create_category(root_level)
  234. parent_id = _text(resp)['id']
  235. children = []
  236. for category_name in second_levels:
  237. child = create_category(category_name)
  238. child_id = _text(child)['id']
  239. update_category(child_id, {
  240. 'parentId': parent_id
  241. })
  242. children.append(child_id)
  243. return children
  244. def create_specific_categories():
  245. categories = []
  246. resp = show_root_categories()
  247. if len(_text(resp)) == 0:
  248. categories.extend(create_2_levels_categories('思政', ['党规党纪', '思想理论', '党史故事']))
  249. categories.extend(create_2_levels_categories('安全', ['劳动安全', '作业安全', '事故案例']))
  250. categories.extend(create_2_levels_categories('理论', ['基础理论', '专业理论']))
  251. categories.extend(create_2_levels_categories('实作', ['作业指导书', '作业技巧', '应急处置']))
  252. categories.extend(create_2_levels_categories('教材', ['文字', '音像', '课件']))
  253. categories.extend(create_2_levels_categories('法纪', ['国家法律', '法纪法规', '交通规则']))
  254. categories.extend(create_2_levels_categories('健康', ['健康知识', '健康养生', '心理辅导']))
  255. categories.extend(create_2_levels_categories('集萃', ['旅游', '摄影','诗词', '名篇']))
  256. else:
  257. print('Skip creating specific categories')
  258. root_categories = _text(resp)
  259. for root_category in root_categories:
  260. categories.append(root_category['id'])
  261. return categories
  262. def read_material_from_file(file_name):
  263. file = open('./demo-materials/' + file_name, 'r')
  264. file_lines = file.readlines()
  265. count = 0
  266. content = ''
  267. title = ''
  268. for line in file_lines:
  269. line = line.strip()
  270. if len(line) < 1:
  271. continue # whitespaces
  272. if count == 0:
  273. title = line
  274. else:
  275. content += line + '\n'
  276. count+=1
  277. return title, content
  278. def random_pick_tags():
  279. tags = ['CeLiangGong', 'DaXingXianLuJiXieSiJi', 'QiaoSuiGong', 'XianLuGong']
  280. return tags[random.randint(0, len(tags)-1)]
  281. def create_learning_materials(namePrefix='测试资料-', number=20, from_file=False):
  282. categories = []
  283. if not from_file:
  284. categories = create_categories()
  285. materials = []
  286. if from_file:
  287. files = os.listdir('./demo-materials/')
  288. categories = create_specific_categories()
  289. for file_name in files:
  290. title, content = read_material_from_file(file_name)
  291. material = create_material({
  292. 'name': title,
  293. 'userId': randomly_pick_user(),
  294. 'type': 'ARTICLE',
  295. 'contents': content,
  296. 'tags': [random_pick_tags()]
  297. })
  298. materialId = _text(material)['id']
  299. # if random number equals to magic number, then add tag 今日必练
  300. if random.randint(0, 10) == 3:
  301. print('going to add tag to material')
  302. add_tag(datetime.today().strftime('%Y%m%d'), materialId=materialId)
  303. materials.append(materialId)
  304. random_category = categories[random.randint(0, len(categories)-1)]
  305. add_material_to_category(random_category, _text(material))
  306. create_comments(materialId)
  307. else:
  308. for i in range(number):
  309. user = randomly_pick_user()
  310. material = create_material({
  311. 'name': namePrefix + _random_string(5),
  312. 'userId': randomly_pick_user(),
  313. 'description': '好看的资料',
  314. 'type': 'ARTICLE',
  315. 'contents': '十年高考三年模拟-' + _random_string(20),
  316. 'links': [_random_string(3), _random_string(3), _random_string(3)]
  317. })
  318. materialId = _text(material)['id']
  319. materials.append(materialId)
  320. random_category = categories[random.randint(0, len(categories)-1)]
  321. add_material_to_category(random_category, _text(material))
  322. create_comments(materialId)
  323. print ('created ' + str(len(materials)) + ' materials: ' + ','.join(materials))
  324. return materials
  325. def create_comments(materialId, namePrefix='[自动生成]', number=5):
  326. dummy_comments = ['我去,这也太酷了!', '我太爱学这个了,老牛了', '这太有意思了,收藏了', '好文,顶一个', '我踩']
  327. for i in range(number):
  328. comment = {
  329. 'userId': randomly_pick_user(),
  330. 'content': dummy_comments[i % len(dummy_comments)]
  331. }
  332. add_comment(materialId, comment)
  333. print('created ' + str(number) + ' comments to material: ' + materialId)
  334. def register_user(userData):
  335. url = WEBSITE_PREFIX + '/user/register'
  336. return requests.post(url, json=userData)
  337. def add_tag(tag, materialId=None, questionId=None, examId=None):
  338. url = WEBSITE_PREFIX + '/tags/' + tag + '?'
  339. if materialId:
  340. url += 'material=' + materialId
  341. if questionId:
  342. url += 'question=' + questionId
  343. if examId:
  344. url += 'exam=' + examId
  345. return requests.post(url)
  346. def remove_tag(tag, materialId=None, questionId=None, examId=None):
  347. url = WEBSITE_PREFIX + '/tags/' + tag + '?'
  348. if materialId:
  349. url += 'material=' + materialId
  350. if questionId:
  351. url += 'question=' + questionId
  352. if examId:
  353. url += 'exam=' + examId
  354. return requests.delete(url)
  355. def get_tag(tag):
  356. url = WEBSITE_PREFIX + '/tags/' + tag
  357. return requests.get(url)
  358. def delete_all_exams():
  359. url = WEBSITE_PREFIX + '/admin/exams'
  360. return requests.delete(url)
  361. def delete_all_questions():
  362. url = WEBSITE_PREFIX + '/admin/questions'
  363. return requests.delete(url)
  364. def delete_all_categories():
  365. url = WEBSITE_PREFIX + '/admin/categories'
  366. return requests.delete(url)
  367. def delete_all_tags():
  368. url = WEBSITE_PREFIX + '/admin/tags'
  369. return requests.delete(url)
  370. def delete_all_materials():
  371. url = WEBSITE_PREFIX + '/admin/materials'
  372. return requests.delete(url)
  373. def delete_all_comments():
  374. url = WEBSITE_PREFIX + '/admin/comments'
  375. return requests.delete(url)
  376. if override:
  377. all_users = json.loads(get_all_users().text)
  378. for user in all_users:
  379. delete_user(user['userName'])
  380. print('deleted all users')
  381. delete_all_exams()
  382. print('deleted all exams')
  383. delete_all_questions()
  384. print('deleted all questions')
  385. delete_all_categories()
  386. print('deleted all categories')
  387. delete_all_tags()
  388. print('deleted all tags')
  389. delete_all_materials()
  390. print('deleted all materials')
  391. delete_all_comments()
  392. print('deleted all comments')
  393. if want_user:
  394. add_dummy_users()
  395. else:
  396. print('Skip creating users')
  397. if want_question:
  398. create_questions(from_file=True)
  399. else:
  400. print('Skip creating questions')
  401. if want_material:
  402. create_learning_materials(from_file=True)
  403. else:
  404. print('Skip creating materials')