예제 #1
0
    def __init__(self,username,password):
        self.courses_url = "http://jwxt.sustc.edu.cn/jsxsd/xkgl/kcjjQuery" # post 方式
        self.course_detail_url = "http://jwxt.sustc.edu.cn/jsxsd/xkgl/kcjjQuery?type=1&kcid=" #"+kcid" post方式
        # javascript:kcjjQueryxq('DDCF2D40E2D049B6B9040E035F1EE345')
        self.details_pattern = re.compile("javascript:kcjjQueryxq\(\'(.*)\'\)")
        #  共2页 22条
        self.page_info_pattern = re.compile("[\u4e00-\u9fa5](\d*)[\u4e00-\u9fa5].(\d*).*")

        self.cfg = Myconf()

        self.session = requests.session()
        self.set_cas_session(username,password)

        self.coding = None

        self.semesters = []
        self.faculties = {}

        # 初始化所以 学期 和 所有 院系
        self.__init_request("./conf/init_request.ini")

        # self.semesters = ["2018-2019-2","2018-2019-1"]

        self.basic_data = {
            "xnxq01id": "",     # important !!! the semester
            "xx0301id": "",     # inportant !!! the faculty
            "kch": "",
            "kcmc": "",
            "jx02id": "",
            "pageIndex": "1",     # important !!! page index( 20 rows / page )
        }

        # courses 类 可将储存的 course 信息直接导入 mongo 数据库
        self.courses = courses.Courses()
    def main(self):
        print(
            'Welcome to AT Academy! How can we help you? \n\n1. What are the courses available? \n2. Enroll me! \n3. Check my information \n4. Mark the program as completed \n5. Exit application \n'
        )
        menuIndex = input('Menu number: ')

        while menuIndex not in ['1', '2', '3', '4', '5']:
            menuIndex = int(
                input('Option unavailable. Please enter a valid option: '))

        print('\n')

        if menuIndex == '1':
            academyCourses.Courses().main()
        elif menuIndex == '2':
            academyStudents.Students().enroll()
        elif menuIndex == '3':
            studentId = input('Enter your student ID: ')
            academyStudents.Students().main(studentId)
        elif menuIndex == '4':
            endProgram = input(
                "The deposits of all the students will be refunded. Proceed? ('Y'-yes/'N'-no): "
            )
            while endProgram not in ['Y', 'N']:
                endProgram = input(
                    "Please enter either 'Y' for yes or 'N' for no: ")
            if endProgram == 'Y':
                academyStudents.Students().graduatestudents()
                print('The program has been marked complete successfully.')
            else:
                self.main()
        elif menuIndex == '5':
            print('We look forward to your visit again!')
예제 #3
0
    def menu(self):
        print(
            "1. Existing Student Information \n2. New Registration \n3. Courses Inquiry\
                \n4. Payment Information \n5. Leave the Course \n6. Exit")
        choice = int(input("Enter the number You would like to know about: "))

        if choice == 1:
            info = self.existingStudentInfo()
            if info == []:
                print(
                    f"Sorry, We don't have a student named {(self.name).title()} in our academy"
                )
            else:
                print(info)
            print("\n")
            self.menu()

        if choice == 2:
            newRegisteredInfo = self.addInfo()
            with open(self.path + '/csvfiles/list.csv', 'a') as write_file:
                csv_writer = csv.writer(write_file)
                headers = ['Name', 'Age', 'Course', 'Balance']
                fileEmpty = os.stat(self.path +
                                    '/csvfiles/list.csv').st_size == 0
                if fileEmpty:
                    csv_writer.writerow(headers)
                csv_writer.writerow(newRegisteredInfo)

                print("Congratulations.You have been registered")
            print("\n")
            self.menu()

        if choice == 3:
            print(cs.Courses().courseInfo())
            print("\n")
            self.menu()

        if choice == 4:
            balance = self.totalDue()
            if isinstance(balance, list):
                print("invalid command")
            elif balance == self.totalCourseBalance:
                print("You have no remaining dues")
            elif (balance >= 10000):
                balance = self.totalCourseBalance - balance
                print("Your Remaining Balance is: Rs", balance)
            print("\n")
            self.menu()

        if choice == 5:
            print(self.leaveProgram())
            print("\n")
            self.menu()

        if choice == 6:
            print("Program Terminated")
            sys.exit()
예제 #4
0
    def enroll(self):
        academyCourses.Courses().displaycourses()

        courseCode = input(
            'Which course do you want to enroll in (use course code)? ')
        studentName = input('Enter your full name: ')
        age = input('Age: ')
        gender = input('Gender (M/F): ')
        amount = input(
            """You can pay for this course in two installments. The total cost is 20,000, but you can pay an installment of 10,000.\nChoose 1 for full payment and 2 for paying in installment: """
        )

        while amount not in ['1', '2']:
            amount = input(
                "Invalid option. Choose 1 for full payment and 2 for paying in installment: "
            )

        amount = 20000 if amount == "1" else 10000

        print(
            f'\nName: {studentName} \nAge: {age} \nGender: {"Male" if gender == "M" else "Female"} \nCourse: {academyCourses.Courses().getcourseinfo(courseCode)[1]} \nAmount: {amount} \n'
        )
        print(
            """Would you like to continue with the enrollment? \n\n1.Yes, this looks good! \n2.I'd like to fill this form again """
        )
        enrollConfirm = int(input('\nYour choice: '))

        if enrollConfirm == 1:
            self.students.append([
                self.generatestudentid(), studentName, age, gender, courseCode,
                amount, 0 if amount == 20000 else 10000, '0'
            ])
            dbcontext.CsvFunctions().writer(
                self.header, self.students,
                self.path + '/Records/Students.csv')
            print(
                f'\nCongratulations! You have been enrolled! Your ID is {self.students[-1][0]}. You can use this ID to view your information from the main menu. \n'
            )

            enrollCompleted = input('Press 1 and Enter to go to main menu: ')
            while enrollCompleted != '1':
                enrollCompleted = input(
                    'Option unavailable. Press 1 and Enter to go to main menu: '
                )
            print('\n')
            academy.Academy().main()
        elif enrollConfirm == 2:
            self.enroll()
예제 #5
0
def enter_record(ans):

    if ans == '1':
        #import from studentData.py
        import studentData as sd
        click.clear()
        #create object for StudentData class and class its function
        s_data = sd.StudentData()
        mycoll = conn.create_collection('Student')
        conn.insert(s_data.record_Dict(), mycoll)
        options()

    if ans == '2':
        #import from teacherData.py
        import teacherData as td
        click.clear()
        #create object for TeacherData class and class its function
        t_data = td.TeacherData()
        mycoll = conn.create_collection('Teachers')
        conn.insert(t_data.record_Dict(), mycoll)
        options()

    if ans == '3':
        #import from courses.py
        import courses as cd
        click.clear()
        #create object for Courses class and class its function
        c_data = cd.Courses()
        mycoll = conn.create_collection('Courses')
        conn.insert(c_data.record_Dict(), mycoll)
        options()

    if ans == '4':

        #import from courseTeacher.py
        import courseTeacher as ct
        click.clear()
        #create object for courseTeacher class and class its function
        ct_data = ct.CourseTeacher()
        mycoll = conn.create_collection('CourseTeacher')
        year, _class, cnic = ct_data.record_Dict()
        conn.insert_classTeacher(year, _class, cnic, mycoll)
        options()
예제 #6
0
def wechat_auth():
    if request.method == 'GET':
        token = 'Add your token here'
        query = request.args
        signature = query.get('signature', '')
        timestamp = query.get('timestamp', '')
        nonce = query.get('nonce', '')
        echostr = query.get('echostr', '')
        s = [timestamp, nonce, token]
        s.sort()
        s = ''.join(s)
        if (hashlib.sha1(s).hexdigest() == signature):
            return make_response(echostr)
    # Get the infomations from the recv_xml.
    reply = config.reply
    xiaoli_reply = config.xiaoli_reply
    bus_reply = ''' '''
    xml_recv = ET.fromstring(request.data)
    ToUserName = xml_recv.find("ToUserName").text
    FromUserName = xml_recv.find("FromUserName").text
    Content = ''
    try:
        Content = xml_recv.find("Content").text
    except:
        pass
    msgtype_test = ''
    event_test = ''
    try:
        msgtype_test = xml_recv.find('MsgType').text
        event_test = xml_recv.find('Event').text
    except:
        pass

    if msgtype_test == 'event' and event_test == 'subscribe':
        # 返回帮助信息
        Content = tips

    elif Content.lower().find('xiaoli') >= 0:
        # 返回图文模式
        # 校历
        response = make_response(
            xiaoli_reply %
            (FromUserName, ToUserName, str(int(time.time())),
             'http://tzclife-pic.stor.sinaapp.com/xiaoli2015.jpg'))
        response.content_type = 'application/xml'
        return response

    elif Content.lower().find('help') >= 0:
        # 返回帮助信息
        Content = tips

    elif Content.lower().find('bir') >= 0:
        # 返回天数
        Content = dateCounts.DateCounts(Content)

    elif Content.lower().find('time') >= 0:
        # 查询校园时间表
        Content = config.TimeTableSummer

    elif Content.lower().find('movie') >= 0:
        # 查询学校电影信息
        Content = config.movies

    elif Content.lower().find('bus') >= 0:
        # 查询公交信息
        Content = config.bus

    elif Content.lower().find('status') >= 0:
        # 向人人网LiveTzc发布状态
        Content = renrenStatus.RenrenStatus(Content)

    elif Content.find('@') >= 0:
        # 查询歌词 用的是百度音乐
        Content = lrcSearch.LrcSearchRequests(Content)

    elif Content.find('dt') >= 0:
        # 查询上海公交卡还剩多少钱
        sptccUrl = 'http://220.248.75.36/handapp/PGcardAmtServlet?arg1='
        success = Content.split()
        if len(success) == 2:
            page = urllib2.urlopen(sptccUrl + success[1]).read()
            page_f = page.find("'")
            page_e = page.find("'", page_f + 1)
            Content = '交通卡还剩下  ' + page[page_f + 1:page_e] + '  元TAT'
        else:
            Content = 'SPTCC error...'

    elif Content.find('car') >= 0:
        # 查询违章信息
        args = Content.split()
        chepai = args[1]
        cjh = args[2]
        post_url = 'http://bsdt.jhga.gov.cn/egov/jdcwfcxAction.action'
        post_data = dict(CPHM='浙G' + chepai,
                         CJH=cjh,
                         CPLB='02',
                         fn='jdcwfcx',
                         OPENID='oDQPZt6mijPGQMBv7cnAOOUBK8g8')
        html = requests.post(post_url, post_data)
        try:
            datas = json.loads(html.content)
            carid = len(datas)
            infos = ''
            for x in range(carid):
                infos = infos + '\n\nwww.jhga.gov.cn/ajax/jxj_showimg.aspx?id=' + str(
                    datas[x]['ID'])
            Content = html.content[:1500] + '\n' + '一共' + str(
                carid) + '个违章\n\n' + infos[:460]
        except:
            Content = html.content[:2000]

    elif Content.lower().find('cjhlist') >= 0:
        # 违章列表
        Content = config.cars

    elif Content.lower().find('sptcc') >= 0:
        # 查询上海公交卡还剩多少钱
        sptccUrl = 'http://220.248.75.36/handapp/PGcardAmtServlet?arg1=49925366539'
        page = urllib2.urlopen(sptccUrl).read()
        page_f = page.find("'")
        page_e = page.find("'", page_f + 1)
        Content = '交通卡还剩下  ' + page[page_f + 1:page_e] + '  元TAT'

    elif Content.lower().find('lib') >= 0:
        # 图书馆相关信息查询
        success = Content.split()
        book_url = 'http://www2.lib.tzc.edu.cn/cgi-bin/IlaswebBib'
        for i in range(len(success)):
            success[i] = success[i].encode('utf8')
        if len(success) == 2:
            book_name = success[1]
            Content = librarySearch.LibrarySearch(book_name)

        elif len(success) == 3:
            try:
                Content = libraryBorrowed(success[1], success[2])
            except:
                Content = '图书馆服务器故障'
        else:
            Content = 'lib和书名之间要有个空格哦!!!'

    elif len(Content.split()) == 2:
        # 返回课表信息
        Content = courses.Courses(Content)
    else:
        Content = error_msg
    # 格式化
    response = make_response(
        reply % (FromUserName, ToUserName, str(int(time.time())), Content))
    response.content_type = 'application/xml'
    return response
예제 #7
0
def delete_record(ans):

    if ans == '7':

        import studentData as sd
        click.clear()
        s_data = sd.StudentData()
        while True:
            #passing string as collection name
            conn.delete(s_data.delete_data(),
                        conn.create_collection('Student'))
            print("\n Deleted! Enter to delete more or Press 'q' to go back")
            #break loop if 'exit' is entered
            if input() == 'q':
                break
            #if enter is pressed start the loop again
            else:
                click.clear()
                continue
        options()

    if ans == '8':

        import teacherData as td
        click.clear()
        t_data = td.TeacherData()
        while True:

            conn.delete(t_data.delete_data(),
                        conn.create_collection('Teachers'))
            print("\n Deleted! Enter to delete more or Press 'q' to go back")
            #break loop if 'exit' is entered
            if input() == 'q':
                break
            #if enter is pressed start the loop again
            else:
                click.clear()
                continue
        options()

    if ans == '9':

        import courses as cd
        click.clear()
        c_data = cd.Courses()
        while True:
            '''
            key,ans = c_data.delete_data()
            
            if ans == '1':
                _no = conn.delete_class(key,'Courses')
                
            if ans =='2':
                _no = conn.delete_course(key,'Courses')
            '''

            key = c_data.delete_data()
            _no = conn.delete_class(key, conn.create_collection('Courses'))

            if _no == '1':
                print(
                    "\n Deleted! Enter to delete more or Press 'q' to go back")

            if _no == '0':
                print(
                    "\n Doesnot Exist! Enter to delete other or Press 'q' to go back"
                )

            #break loop if 'exit' is entered
            if input() == 'q':
                break
            #if enter is pressed start the loop again
            else:
                click.clear()
                continue
        options()

    if ans == '10':

        import courseTeacher as ct
        click.clear()
        ct_data = ct.CourseTeacher()
        while True:

            conn.delete(ct_data.delete_data(),
                        conn.create_collection('CourseTeacher'))
            print("\n Deleted! Enter to delete more or Press 'q' to go back")
            #break loop if 'exit' is entered
            if input() == 'q':
                break
            #if enter is pressed start the loop again
            else:
                click.clear()
                continue
        options()