setup_db.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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, encoding="UTF-8") as read_obj:
  116. print('loading ' + file_name + ' to db')
  117. exam_tag = file_name.split('-')[1]
  118. exam_prefix = file_name.split('-')[0]
  119. exams = create_exams(namePrefix=exam_prefix + '-' + exam_tag, number=6, tags=[exam_tag])
  120. csv_reader = reader(read_obj)
  121. for row in csv_reader:
  122. qNumber = row[0]
  123. if qNumber == '题号' or len(qNumber) < 1:
  124. continue
  125. content = row[1] # required
  126. temp_type = row[2] # required
  127. qType = 'DanXuan'
  128. if temp_type == '2':
  129. qType = 'DuoXuan'
  130. if temp_type == '3':
  131. qType = 'PanDuan'
  132. answers = [] # required
  133. for i in [3, 4, 5, 6]:
  134. if len(row[i]) > 0:
  135. answers.append(row[i])
  136. finalAnswer = row[7] # required
  137. answerAnalysis = row[8]
  138. keyword = row[9];
  139. level = row[10];
  140. tags = []
  141. if len(row[11]) > 0:
  142. if row[11] == '线路工':
  143. tags.append('XianLuGong')
  144. elif row[11] == '桥隧工':
  145. tags.append('QiaoSuiGong')
  146. elif row[11] == '大型线路机械司机':
  147. tags.append('DaXingXianLuJiXieSiJi')
  148. elif row[11] == '测量工':
  149. tags.append('CeLiangGong')
  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. add_tag(datetime.today().strftime('%Y%m%d'), questionId=_text(resp)['id'])
  172. # add newly created question to a random exam
  173. add_question_to_exam(random_exam_id, [exam_to_question])
  174. questions.append(_text(resp)['id'])
  175. else:
  176. for i in range(number):
  177. question = {
  178. 'userId': randomly_pick_user(),
  179. 'content': namePrefix + '天上什么星星最亮?-' + str(i),
  180. 'answers': ['太阳', '小天狼星', '北极星'],
  181. 'finalAnswer': ['小天狼星'],
  182. 'type': 'DanXuan' # 单选题
  183. }
  184. resp = create_question(question)
  185. random_exam_id = exams[random.randint(0, len(exams)-1)]
  186. # add newly created question to a random exam
  187. add_question_to_exam(random_exam_id, [_text(resp)])
  188. questions.append(_text(resp)['id'])
  189. tiankong_question = {
  190. 'userId': randomly_pick_user(),
  191. 'content': namePrefix + '天上$PH$最亮?-' + str(i),
  192. 'finalAnswer': ['小天狼星'],
  193. 'type': 'TianKong' # 填空题
  194. }
  195. resp = create_question(tiankong_question)
  196. random_exam_id = exams[random.randint(0, len(exams)-1)]
  197. # add newly created question to a random exam
  198. add_question_to_exam(random_exam_id, [_text(resp)])
  199. random_category_id = question_categories[random.randint(0, len(question_categories)-1)]
  200. add_question_to_question_category(random_category_id, _text(resp))
  201. questions.append(_text(resp)['id'])
  202. print ('created ' + str(len(questions)) + ' questions')
  203. return questions
  204. def create_question_categories(namePrefix= '知识类-', number=3):
  205. resp = create_question_category(namePrefix + _random_string(3))
  206. question_root_id = _text(resp)['id']
  207. categories = []
  208. names = ['科普类-', '技术类-', '历史类-', '天文类-', '兴趣类-']
  209. for i in range(number):
  210. child = create_question_category(names[i % len(names)] + _random_string(3))
  211. child_id = _text(child)['id']
  212. update_question_category(child_id, {
  213. 'parentId': question_root_id
  214. })
  215. categories.append(child_id)
  216. print ('created ' + str(len(categories)) + ' question categories: ' + ','.join(categories))
  217. return categories
  218. def create_categories(namePrefix= 'testCategory-', number=3):
  219. resp = create_category(namePrefix + 'root-' + _random_string(3))
  220. root_id = _text(resp)['id']
  221. categories = []
  222. for i in range(number):
  223. child = create_category(namePrefix + 'child-' + _random_string(3))
  224. child_id = _text(child)['id']
  225. update_category(child_id, {
  226. 'parentId': root_id
  227. })
  228. categories.append(child_id)
  229. print ('created ' + str(len(categories)) + ' categories: ' + ','.join(categories))
  230. return categories
  231. def create_2_levels_categories(root_level, second_levels):
  232. resp = create_category(root_level)
  233. parent_id = _text(resp)['id']
  234. children = []
  235. for category_name in second_levels:
  236. child = create_category(category_name)
  237. child_id = _text(child)['id']
  238. update_category(child_id, {
  239. 'parentId': parent_id
  240. })
  241. children.append(child_id)
  242. return children
  243. def create_specific_categories():
  244. categories = []
  245. resp = show_root_categories()
  246. if len(_text(resp)) == 0:
  247. categories.extend(create_2_levels_categories('思政', ['党规党纪', '思想理论', '党史故事']))
  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. else:
  256. print('Skip creating specific categories')
  257. root_categories = _text(resp)
  258. for root_category in root_categories:
  259. categories.append(root_category['id'])
  260. return categories
  261. def read_material_from_file(file_name):
  262. file = open('./demo-materials/' + file_name, encoding="UTF-8")
  263. file_lines = file.readlines()
  264. count = 0
  265. content = ''
  266. title = ''
  267. for line in file_lines:
  268. line = line.strip()
  269. if len(line) < 1:
  270. continue # whitespaces
  271. if count == 0:
  272. title = line
  273. else:
  274. content += line + '\n'
  275. count+=1
  276. return title, content
  277. def create_learning_materials(namePrefix='测试资料-', number=20, from_file=False):
  278. categories = []
  279. if not from_file:
  280. categories = create_categories()
  281. materials = []
  282. if from_file:
  283. files = os.listdir('./demo-materials/')
  284. categories = create_specific_categories()
  285. for file_name in files:
  286. title, content = read_material_from_file(file_name)
  287. material = create_material({
  288. 'name': title,
  289. 'userId': randomly_pick_user(),
  290. 'type': 'ARTICLE',
  291. 'contents': content,
  292. })
  293. materialId = _text(material)['id']
  294. # if random number equals to magic number, then add tag 今日必练
  295. if random.randint(0, 10) == 3:
  296. add_tag(datetime.today().strftime('%Y%m%d'), materialId=materialId)
  297. materials.append(materialId)
  298. random_category = categories[random.randint(0, len(categories)-1)]
  299. add_material_to_category(random_category, _text(material))
  300. create_comments(materialId)
  301. else:
  302. for i in range(number):
  303. user = randomly_pick_user()
  304. material = create_material({
  305. 'name': namePrefix + _random_string(5),
  306. 'userId': randomly_pick_user(),
  307. 'description': '好看的资料',
  308. 'type': 'ARTICLE',
  309. 'contents': '十年高考三年模拟-' + _random_string(20),
  310. 'links': [_random_string(3), _random_string(3), _random_string(3)]
  311. })
  312. materialId = _text(material)['id']
  313. materials.append(materialId)
  314. random_category = categories[random.randint(0, len(categories)-1)]
  315. add_material_to_category(random_category, _text(material))
  316. create_comments(materialId)
  317. print ('created ' + str(len(materials)) + ' materials: ' + ','.join(materials))
  318. return materials
  319. def create_comments(materialId, namePrefix='[自动生成]', number=5):
  320. dummy_comments = ['我去,这也太酷了!', '我太爱学这个了,老牛了', '这太有意思了,收藏了', '好文,顶一个', '我踩']
  321. for i in range(number):
  322. comment = {
  323. 'userId': randomly_pick_user(),
  324. 'content': dummy_comments[i % len(dummy_comments)]
  325. }
  326. add_comment(materialId, comment)
  327. print('created ' + str(number) + ' comments to material: ' + materialId)
  328. def register_user(userData):
  329. url = WEBSITE_PREFIX + '/user/register'
  330. return requests.post(url, json=userData)
  331. def add_tag(tag, materialId=None, questionId=None, examId=None):
  332. url = WEBSITE_PREFIX + '/tags/' + tag + '?'
  333. if materialId:
  334. url += 'material=' + materialId
  335. if questionId:
  336. url += 'question=' + questionId
  337. if examId:
  338. url += 'exam=' + examId
  339. return requests.post(url)
  340. def remove_tag(tag, materialId=None, questionId=None, examId=None):
  341. url = WEBSITE_PREFIX + '/tags/' + tag + '?'
  342. if materialId:
  343. url += 'material=' + materialId
  344. if questionId:
  345. url += 'question=' + questionId
  346. if examId:
  347. url += 'exam=' + examId
  348. return requests.delete(url)
  349. def get_tag(tag):
  350. url = WEBSITE_PREFIX + '/tags/' + tag
  351. return requests.get(url)
  352. def delete_all_exams():
  353. url = WEBSITE_PREFIX + '/admin/exams'
  354. return requests.delete(url)
  355. def delete_all_questions():
  356. url = WEBSITE_PREFIX + '/admin/questions'
  357. return requests.delete(url)
  358. def delete_all_categories():
  359. url = WEBSITE_PREFIX + '/admin/categories'
  360. return requests.delete(url)
  361. def delete_all_tags():
  362. url = WEBSITE_PREFIX + '/admin/tags'
  363. return requests.delete(url)
  364. def delete_all_materials():
  365. url = WEBSITE_PREFIX + '/admin/materials'
  366. return requests.delete(url)
  367. def delete_all_comments():
  368. url = WEBSITE_PREFIX + '/admin/comments'
  369. return requests.delete(url)
  370. if override:
  371. all_users = json.loads(get_all_users().text)
  372. for user in all_users:
  373. delete_user(user['userName'])
  374. print('deleted all users')
  375. delete_all_exams()
  376. print('deleted all exams')
  377. delete_all_questions()
  378. print('deleted all questions')
  379. delete_all_categories()
  380. print('deleted all categories')
  381. delete_all_tags()
  382. print('deleted all tags')
  383. delete_all_materials()
  384. print('deleted all materials')
  385. delete_all_comments()
  386. print('deleted all comments')
  387. if want_user:
  388. add_dummy_users()
  389. else:
  390. print('Skip creating users')
  391. if want_question:
  392. create_questions(from_file=True)
  393. else:
  394. print('Skip creating questions')
  395. if want_material:
  396. create_learning_materials(from_file=True)
  397. else:
  398. print('Skip creating materials')