Пример #1
0
    def getStudentGrade(self):
        urlsuffix = getSelectUrl(self.Loginresponse, u'成绩查询')
        url = self.baseUrl + '/' + urlsuffix
        self.session.headers['Referer'] = self.baseUrl + "/xs_main.aspx?xh=" + self.student.studentnumber
        response = self.session.get(url)
        __VIEWSTATE = get__VIEWSTATE(response)
        self.session.headers['Referer'] = url
        data = {
            "__EVENTTARGET":"",
            "__EVENTARGUMENT":"",
            "__VIEWSTATE":__VIEWSTATE,
            "__VIEWSTATEGENERATOR" : "9727EB43",
            'hidLanguage':"",
            "ddlXN":"",
            "ddlXQ":"",
            "ddl_kcxz":"",
            "btn_zcj" : u"历年成绩".encode('gb2312', 'replace')
        }
        response = self.session.post(url,data=data)
        grades = getGrade(response)
        for onegrade in grades:
            year = onegrade["year"]
            term = onegrade["term"]
            classNo = onegrade["classNo"]
            try:
                yearGrade = YearGrade.get(YearGrade.year == year , YearGrade.student == self.student)
            except:
                yearGrade = YearGrade(year=year,student=self.student)
                yearGrade.save()
            try:
                termGrade = TermGrade.get(TermGrade.year == yearGrade , TermGrade.term == int(term))
            except:
                termGrade = TermGrade(year = yearGrade ,term = int(term))
                termGrade.save()
            try:
                lesson = Class.get(Class.classNo == classNo)
            except:
                schedule = ClassSchedule.get(ClassSchedule.year == year, ClassSchedule.term == term)
                lesson = Class(schedule=schedule, classNo=classNo, name=onegrade["name"]
                              ,type=onegrade["type"], point=float(onegrade["credit"]))
                lesson.save()

            try:
                gradePoint = float(onegrade["gradePonit"])
            except:
                gradePoint = None

            try:
                grade = float(onegrade["grade"])
            except:
                grade = None

            oneLessonGrade = OneLessonGrade(lesson=lesson, term=termGrade, gradePoint=gradePoint,
                                             grade=grade)
            oneLessonGrade.save()
        return 'ok'
Пример #2
0
 def getClassSchedule(self):
     self.session.headers['Referer'] = self.baseUrl+"/xs_main.aspx?xh="+self.student.studentnumber
     urlsuffix = getSelectUrl(self.Loginresponse, u'学生选课情况查询')
     url = self.baseUrl + '/' + urlsuffix
     response = self.session.get(url)
     parsedict = getClassScheduleFromHtml(response)
     __VIEWSTATE = parsedict["__VIEWSTATE"]
     __EVENTTARGET = "ddlXQ"
     year = int(self.student.gradeClass)
     term = 1
     today = datetime.date.today()
     while today.year>year or (today.year==year and today.month>=7 and term==1):
         data = {
             "__EVENTTARGET": __EVENTTARGET,
             "__EVENTARGUMENT": "",
             "__VIEWSTATEGENERATOR" : "FDD5582C",
             "__VIEWSTATE": __VIEWSTATE,
             "ddLXN": str(year)+"-"+str(year+1),
             "ddLXQ": str(term),
         }
         self.session.headers['Referer'] = url
         response = self.session.post(url,data)
         print "正在获取"+str(year)+"-"+str(year+1)+"学年第"+str(term)+"学期课表"
         parsedict = getClassScheduleFromHtml(response)
         if parsedict != None:
             classes = parsedict["classes"]
         else:
             continue
         __VIEWSTATE = getClassScheduleFromHtml(response)["__VIEWSTATE"]
         classSchedule = ClassSchedule(student=self.student,year=str(year)+"-"+str(year+1),term=term)
         classSchedule.save()
         for each in classes:
             #debug
             #try:
             oneClass = Class(schedule=classSchedule , selectClassCode=each["selectClassCode"],
                          classNo=each["classNo"],name=each["name"], type=each["type"],
                          Compulsory= each["Compulsory"],teacher=each["teacher"], point=each["point"],
                          totalTimeInWeek=each["totalTimeInWeek"], timeInTheWeek = each["timeInTheWeek"],
                          timeInTheDay = each["timeInTheDay"], timeInTheTerm=each["timeInTheTerm"],
                          location=each["location"])
             oneClass.save()
             #except KeyError as e:
                 #print each
                 #raise KeyError
         term = term + 1
         if term>2:
             term = 1
             year = year+1
             __EVENTTARGET = "ddlXQ"
         else:
             __EVENTTARGET = "ddlXN"
     return 'ok'
Пример #3
0
def getClassSchedule():
    session.headers['Referer'] = baseUrl + "/xs_main.aspx?xh=" + student.stuNumber
    url = baseUrl + "/tjkbcx.aspx?xh=" + student.stuNumber + "&xm=" + student.urlName + "&gnmkdm=N121605"
    response = session.get(url, allow_redirects=False)
    viewState = getClassScheduleFromHtml(response)["__VIEWSTATE"]
    content=getClassScheduleFromHtml(response)["content"]

    data = {
        "__VIEWSTATE": viewState,
    }

    classes = getClassFileName(student.stuNumber)
    # 课程表文件名
    oneClass = Class(filename=classes,content=content)
    oneClass.save()

    print "成功获取课表"
Пример #4
0
 def getClassSchedule(self):
     self.session.headers[
         'Referer'] = self.baseUrl + "/xs_main.aspx?xh=" + self.student.studentnumber
     url = self.baseUrl + "/xskbcx.aspx?xh=" + self.student.studentnumber + "&xm=" + self.student.urlName + "&gnmkdm=N121603"
     response = self.session.get(url, allow_redirects=False)
     __VIEWSTATE = getClassScheduleFromHtml(response)["__VIEWSTATE"]
     year = int(self.student.gradeClass)
     term = 1
     today = datetime.date.today()
     while today.year > year or (today.year == year and today.month >= 7
                                 and term == 1):
         data = {
             "__EVENTTARGET": "xqd",
             "__EVENTARGUMENT": "",
             "__VIEWSTATE": __VIEWSTATE,
             "xnd": str(year) + "-" + str(year + 1),
             "xqd": str(term),
         }
         self.session.headers['Referer'] = url
         response = self.session.post(url, data)
         print("正在获取" + str(year) + "-" + str(year + 1) + "学年第" +
               str(term) + "学期课表")
         classes = getClassScheduleFromHtml(response)["classes"]
         __VIEWSTATE = getClassScheduleFromHtml(response)["__VIEWSTATE"]
         classSchedule = ClassSchedule(student=self.student,
                                       year=str(year) + "-" + str(year + 1),
                                       term=term)
         classSchedule.save()
         for each in classes:
             oneClass = Class(schedule=classSchedule,
                              name=each["name"],
                              type=each["type"],
                              timeInTheWeek=each["timeInTheWeek"],
                              timeInTheDay=each["timeInTheDay"],
                              timeInTheTerm=each["timeInTheTerm"],
                              teacher=each["teacher"],
                              location=each["location"])
             oneClass.save()
         term = term + 1
         if term > 2:
             term = 1
             year = year + 1
     print("成功获取课表")
Пример #5
0
def set_up_domains():
    classes = []
    for i in subjects:
        lector = list(filter(lambda t: i["name"] in t["lector"], teachers))
        practices_teachers = list(
            filter(
                lambda t: i["name"] in t["lector"] or i["name"] in t[
                    "practices"], teachers))
        classes.append(
            Class(
                Subject(lector[0]["name"], i["name"], i["students"], 0,
                        i["groups"]), None))
        for j in range(i["groups"]):
            classes.append(
                Class(
                    Subject(
                        practices_teachers[random.randint(
                            0,
                            len(practices_teachers) - 1)]["name"], i["name"],
                        i["students"] // i["groups"], j + 1, i["groups"]),
                    None))
    return classes
Пример #6
0
def register_class():
    error = None
    if request.method == 'POST':
        error = None
        if not request.form['className']:
            error = 'You have to enter a class name'
        elif not request.form['code']:
            error = 'You have to enter a course code'
        elif not request.form['teacherName']:
            error = 'You have to enter a teacher\'s name'
        elif not request.form['startHours'] or not request.form['startHours']:
            error = 'You have to enter the start time'
        elif not request.form['endHours'] or not request.form['endHours']:
            error = 'You have to enter the end time'
        else:
            teacher = User.query.filter_by(
                username=request.form['teacherName']).first()
            if teacher and teacher.userType == "t":
                timeStart = request.form['startHours'] + request.form[
                    'startHours']
                timeEnd = request.form['endHours'] + request.form['endHours']
                if timeStart < timeEnd:
                    db.session.add(
                        Class(name=request.form['className'],
                              code=request.form['code'],
                              teacherID=teacher.id,
                              startTime=timeStart,
                              endTime=timeEnd))
                    db.session.commit()
                    flash('You were successfully added a class')
                else:
                    error = "The end time must be later than the start time"
            else:
                error = "That teacher username does not exist"
    teachers = User.query.filter_by(userType='t').all()
    return render_template("register_class.html",
                           user=g.user,
                           error=error,
                           teachers=teachers)
Пример #7
0
def load_data(file_path, teachers_empty_space, groups_empty_space,
              subjects_order):
    """
    Loads and processes input data, initialises helper structures.
    :param file_path: path to file with input data
    :param teachers_empty_space: dictionary where key = name of the teacher, values = list of rows where it is in
    :param groups_empty_space: dictionary where key = group index, values = list of rows where it is in
    :param subjects_order: dictionary where key = (name of the subject, index of the group), value = [int, int, int]
    where ints represent start times (row in matrix) for types of classes P, V and L respectively. If start time is -1
    it means that that subject does not have that type of class.
    :return: Data(groups, teachers, classes, classrooms)
    """
    with open(file_path) as file:
        data = json.load(file)

    # classes: dictionary where key = index of a class, value = class
    classes = {}
    # classrooms: dictionary where key = index, value = classroom name
    classrooms = {}
    # teachers: dictionary where key = teachers' name, value = index
    teachers = {}
    # groups: dictionary where key = name of the group, value = index
    groups = {}
    class_list = []

    for cl in data['Time']:
        new_group = cl['Group']
        new_teacher = cl['Teacher']

        # initialise for empty space of teachers
        if new_teacher not in teachers_empty_space:
            teachers_empty_space[new_teacher] = []

        new = Class(new_group, new_teacher, cl['Subject'], cl['Type'],
                    cl['Duration'], cl['Classroom'])
        # add groups
        for group in new_group:
            if group not in groups:
                groups[group] = len(groups)
                # initialise for empty space of groups
                groups_empty_space[groups[group]] = []

        # add teacher
        if new_teacher not in teachers:
            teachers[new_teacher] = len(teachers)
        class_list.append(new)

    # shuffle mostly because of teachers
    random.shuffle(class_list)
    # add classrooms
    for cl in class_list:
        classes[len(classes)] = cl

    # every class is assigned a list of classrooms he can be in as indexes (later columns of matrix)
    for type in data['Classrooms']:
        for name in data['Classrooms'][type]:
            new = Classroom(name, type)
            classrooms[len(classrooms)] = new

    # every class has a list of groups marked by its index, same for classrooms
    for i in classes:
        cl = classes[i]

        classroom = cl.classrooms
        index_classrooms = []
        # add classrooms
        for index, c in classrooms.items():
            if c.type == classroom:
                index_classrooms.append(index)
        cl.classrooms = index_classrooms

        class_groups = cl.groups
        index_groups = []
        for name, index in groups.items():
            if name in class_groups:
                # initialise order of subjects
                if (cl.subject, index) not in subjects_order:
                    subjects_order[(cl.subject, index)] = [-1, -1, -1]
                index_groups.append(index)
        cl.groups = index_groups

    return Data(groups, teachers, classes, classrooms)
Пример #8
0
def enter_courses_into_db():
    for id, name in COURSES.items():
        cl = Class(id=id, name=name)
        db.add(cl)
    db.commit()
Пример #9
0
    titlenode = utils.getFirstDescendant(sub, "class-title")

    titletext = getTitleText(titlenode)
    # create a new subsection
    subsection = Subsection(subsectionsymbol, titletext)
    # many to one rela
    section.subsections.append(subsection)

    classlist = sub.findall('classification-item')
    for clas in classlist:
        classsymbol = clas.find("classification-symbol").text
        classtitle = clas.find('class-title')
        classdesc = getTitleText(classtitle)
        print classdesc

        newclass = Class(classsymbol, classdesc)

        subclasslist = clas.findall('classification-item')

        for subclass in subclasslist:
            subclasssymbol = subclass.find('classification-symbol').text
            subclasstitle = subclass.find('class-title')
            subclassdesc = getTitleText(subclasstitle)

            newsubclass = Subclass(subclasssymbol, subclassdesc)
            session.add(newsubclass)
            newclass.subclasses.append(newsubclass)

        session.add(newclass)
        subsection.classes.append(newclass)
    session.add(subsection)
Пример #10
0
import contextlib
from model import User, Class, Tutor, Registered, Tutoring, Base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import MetaData

engine = create_engine('sqlite:///sqlalchemy_example.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
db = DBSession()
tutors = db.query(Tutor).filter_by(class_id='CSE128').all()
print(tutors)
test_user = User(id=1, name='Priya', email='*****@*****.**')
test_user1 = User(id=2, name='Austin', email='*****@*****.**')
test_class = Class(id='CS128', name='CS128')
test_class1 = Class(id='CS133', name='CS133')
test_tutor = Tutor(id=1, name='Priya', class_id='CSE128')
test_tutor1 = Tutor(id=2, name='Austin', class_id='CSE133')
test_tutor3 = Tutor(id=3, name='zoowee', class_id='CSE128')
db.add(test_user)
db.add(test_user1)
db.add(test_class)
db.add(test_class1)
db.add(test_tutor)
db.add(test_tutor1)
db.add(test_tutor3)
db.commit()
tutors = db.query(Tutor).filter_by(class_id='CSE128').all()
print(tutors)