import pymysql import json # from jsonencoder import JsonEncoder class ZkTools(): db=None def __init__(self): self.db = pymysql.connect(host="localhost", user="user", password="password", db="zk") def get_courses(self): cursor=self.db.cursor() sql="select `data` from `course`" cursor.execute(sql) data=cursor.fetchone()[0] data=json.loads(data) self.db.commit() res=[] for i in data['results']: res.append({'id':i['id'], 'name':i['name']}) return res def get_questions(self, course_id): cursor=self.db.cursor() sql="select `data` from `question_list` where `course_id` = %s" cursor.execute(sql, course_id) data=cursor.fetchone()[0] data=json.loads(data) self.db.commit() res=[] for i in data['results']: res.append({'id':i['id'], 'name':i['title']}) return res def get_content(self, question_id): cursor=self.db.cursor() sql="select `content_object` from `question_content_object` where `question_id` = %s" cursor.execute(sql, question_id) data=cursor.fetchone()[0] data=json.loads(data) self.db.commit() return data def format(self, data): # data=data["data"] temp="

%s

\n" % data['title'] # memo1 if data["memo"] != "": temp+="

%s

\n" % data["memo"] # groups temp+="
\n" for group_index in range(0, len(data['groups'])): group=data['groups'][group_index] temp+="

%s

\n" % group['title'] if group['memo'] != "": temp+="

%s

\n" % group['memo'] # questions temp+="
\n" for question_index in range(0, len(group['questions'])): question=group['questions'][question_index] temp+="

%s. %s

\n" %(question_index+1, question['title']) temp+="\n" for answer_index in range(0,len(question['answer'])): answer=question['answer'][answer_index] if type(answer) == list: question['answer'][answer_index]=";".join(question['answer'][answer_index]) temp+="

答案:%s

\n" % (";".join(question['answer'])) if 'explanation' in question: temp+="

题解:%s

\n" % (question['explanation']) temp+= "
\n" if question_index < len(group['questions'])-1 else "" temp+="
\n" temp+="
\n" return temp