zktools.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import pymysql
  2. import json
  3. # from jsonencoder import JsonEncoder
  4. class ZkTools():
  5. db=None
  6. def __init__(self):
  7. self.db = pymysql.connect(host="localhost", user="user",
  8. password="password", db="zk")
  9. def get_courses(self):
  10. cursor=self.db.cursor()
  11. sql="select `data` from `course`"
  12. cursor.execute(sql)
  13. data=cursor.fetchone()[0]
  14. data=json.loads(data)
  15. self.db.commit()
  16. res=[]
  17. for i in data['results']:
  18. res.append({'id':i['id'], 'name':i['name']})
  19. return res
  20. def get_questions(self, course_id):
  21. cursor=self.db.cursor()
  22. sql="select `data` from `question_list` where `course_id` = %s"
  23. cursor.execute(sql, course_id)
  24. data=cursor.fetchone()[0]
  25. data=json.loads(data)
  26. self.db.commit()
  27. res=[]
  28. for i in data['results']:
  29. res.append({'id':i['id'], 'name':i['title']})
  30. return res
  31. def get_content(self, question_id):
  32. cursor=self.db.cursor()
  33. sql="select `content_object` from `question_content_object` where `question_id` = %s"
  34. cursor.execute(sql, question_id)
  35. data=cursor.fetchone()[0]
  36. data=json.loads(data)
  37. self.db.commit()
  38. return data
  39. def format(self, data):
  40. # data=data["data"]
  41. temp="<h1>%s</h1>\n" % data['title']
  42. # memo1
  43. if data["memo"] != "":
  44. temp+="<p>%s</p>\n" % data["memo"]
  45. # groups
  46. temp+="<div>\n"
  47. for group_index in range(0, len(data['groups'])):
  48. group=data['groups'][group_index]
  49. temp+="<h2>%s</h2>\n" % group['title']
  50. if group['memo'] != "":
  51. temp+="<p>%s</p>\n" % group['memo']
  52. # questions
  53. temp+="<div>\n"
  54. for question_index in range(0, len(group['questions'])):
  55. question=group['questions'][question_index]
  56. temp+="<p style=\"font-weight:bold;\">%s. %s</p>\n" %(question_index+1, question['title'])
  57. temp+="<ul>\n"
  58. for option in question['options']:
  59. temp+="<li>%s. %s</li>\n" % (option['value'], option['text'])
  60. temp+="</ul>\n"
  61. for answer_index in range(0,len(question['answer'])):
  62. answer=question['answer'][answer_index]
  63. if type(answer) == list:
  64. question['answer'][answer_index]=";".join(question['answer'][answer_index])
  65. temp+="<p><b>答案:</b>%s</p>\n" % (";".join(question['answer']))
  66. if 'explanation' in question:
  67. temp+="<p><b>题解:</b>%s</p>\n" % (question['explanation'])
  68. temp+= "<hr></hr>\n" if question_index < len(group['questions'])-1 else ""
  69. temp+="</div>\n"
  70. temp+="</div>\n"
  71. return temp