From 816e4034c5713470b4754a5c7bd5559f17988cc5 Mon Sep 17 00:00:00 2001 From: Ting-Jun Wang Date: Fri, 25 Jun 2021 08:19:07 +0800 Subject: [PATCH] fix: change Login method --- api/moodle.py | 14 ++++++++------ main.py | 18 +++++------------- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/api/moodle.py b/api/moodle.py index 427bbe4..c731e3e 100644 --- a/api/moodle.py +++ b/api/moodle.py @@ -3,15 +3,14 @@ from bs4 import BeautifulSoup from api.tools import getUrlParam, findAll, find class Moodle(): - def __init__(self): + def __init__(self, username, password): ''' Create a Moodle object to handle Session self.session handle cookies ''' self.session = requests.Session() - # get login token, token is used for self.login() - response = self.session.get('https://moodle.ncnu.edu.tw/') - self.loginToken = find(response, 'input', {'name': 'logintoken'}).get('value') + self.status = self.login(username, password) + def login(self, username, password): ''' @@ -20,10 +19,14 @@ class Moodle(): return True if Login Success ''' + # get login token + response = self.session.get('https://moodle.ncnu.edu.tw/') + loginToken = find(response, 'input', {'name': 'logintoken'}).get('value') + response = self.session.post( 'https://moodle.ncnu.edu.tw/login/index.php?authldap_skipntlmsso=1', data={ - 'logintoken': self.loginToken, + 'logintoken': loginToken, 'username': username, 'password': password } @@ -34,7 +37,6 @@ class Moodle(): self.sessionKey = getUrlParam( find(response, 'a', {'data-title': 'logout,moodle'}).get('href'), 'sesskey' ) - print(self.sessionKey) return True else: return False diff --git a/main.py b/main.py index 4f78984..b7110b8 100644 --- a/main.py +++ b/main.py @@ -1,17 +1,9 @@ from config import CONFIG from api.moodle import Moodle -moodle = Moodle() - -if moodle.login(CONFIG['moodle']['username'], CONFIG['moodle']['password']): - print("登入成功") - courses = moodle.getCourses("1092") - for c in courses: +moodle = Moodle(CONFIG['moodle']['username'], CONFIG['moodle']['password']) +if moodle.status: + for c in moodle.getCourses("1092"): print(c) - events = moodle.getUpcomingEvents() - for e in events: - print(e) -else: - print("登入失敗") - - + for e in moodle.getUpcomingEvents(): + print(e) \ No newline at end of file