moodleNotifer
Public Member Functions | Static Public Member Functions | Public Attributes | Static Public Attributes | List of all members
generatetoken.RequestHelper Class Reference

This Function is used to Generate Token to access moodle account of the student. More...

Public Member Functions

def __init__ (self, str moodle_domain, str moodle_path='/', str token='', bool skip_cert_verify=False, str log_responses_to=None)
 
def post_URL (self, str url, {str:str} data=None, str cookie_jar_path=None)
 
def get_URL (self, str url, str cookie_jar_path=None)
 
object post_REST (self, str function, {str:str} data=None)
 
object get_login (self, {str:str} data)
 
float get_simple_moodle_version (self)
 

Static Public Member Functions

def recursive_urlencode (data)
 

Public Attributes

 token
 
 moodle_domain
 
 moodle_path
 
 verify
 
 url_base
 
 log_responses_to
 
 log_responses
 

Static Public Attributes

dictionary stdHeader
 

Detailed Description

This Function is used to Generate Token to access moodle account of the student.

Encapsulates the recurring logic for sending out requests to the
Moodle-System.

Definition at line 20 of file generatetoken.py.

Member Function Documentation

◆ get_login()

object generatetoken.RequestHelper.get_login (   self,
{str: str}  data 
)
Sends a POST request to the login endpoint of the Moodle system to
obtain a token in JSON format.
@param data: The data is inserted into the Post-Body as arguments. This
should contain the login data.
@return: The JSON response returned by the Moodle System, already
checked for errors.

Definition at line 172 of file generatetoken.py.

172  def get_login(self, data: {str: str}) -> object:
173  """
174  Sends a POST request to the login endpoint of the Moodle system to
175  obtain a token in JSON format.
176  @param data: The data is inserted into the Post-Body as arguments. This
177  should contain the login data.
178  @return: The JSON response returned by the Moodle System, already
179  checked for errors.
180  """
181 
182  response = requests.post(
183  '%slogin/token.php' % (self.url_base),
184  data=urllib.parse.urlencode(data),
185  headers=self.stdHeader,
186  verify=self.verify,
187  )
188 
189  return self._initial_parse(response)
190 

◆ get_simple_moodle_version()

float generatetoken.RequestHelper.get_simple_moodle_version (   self)
Query the version by looking up the change-log (/lib/upgrade.txt)
of the Moodle
@return: a float number representing the newest version
         parsed from the change-log

Definition at line 202 of file generatetoken.py.

202  def get_simple_moodle_version(self) -> float:
203  """
204  Query the version by looking up the change-log (/lib/upgrade.txt)
205  of the Moodle
206  @return: a float number representing the newest version
207  parsed from the change-log
208  """
209 
210  url = '%slib/upgrade.txt' % (self.url_base)
211  response = requests.get(url, headers=self.stdHeader, verify=self.verify)
212 
213  self._check_response_code(response)
214 
215  changelog = str(response.text).split('\n')
216  version_string = '1'
217  for line in changelog:
218  match = re.match(r'^===\s*([\d\.]+)\s*===$', line)
219  if match:
220  version_string = match.group(1)
221  break
222 
223  majorVersion = version_string.split('.')[0]
224  minorVersion = version_string[len(majorVersion) :].replace('.', '')
225 
226  version = float(majorVersion + '.' + minorVersion)
227  return version
228 

◆ get_URL()

def generatetoken.RequestHelper.get_URL (   self,
str  url,
str   cookie_jar_path = None 
)
Sends a GET request to a specific URL of the Moodle system, including additional cookies
(cookies are updated after the request)
@param url: The url to which the request is sent. (the moodle base url is not added to the given URL)
@param cookie_jar_path: The optional cookies to add to the request
@return: The resulting Response object.

Definition at line 93 of file generatetoken.py.

93  def get_URL(self, url: str, cookie_jar_path: str = None):
94  """
95  Sends a GET request to a specific URL of the Moodle system, including additional cookies
96  (cookies are updated after the request)
97  @param url: The url to which the request is sent. (the moodle base url is not added to the given URL)
98  @param cookie_jar_path: The optional cookies to add to the request
99  @return: The resulting Response object.
100  """
101 
102  session = requests.Session()
103 
104  if cookie_jar_path is not None:
105  session.cookies = MozillaCookieJar(cookie_jar_path)
106 
107  if os.path.exists(cookie_jar_path):
108  session.cookies.load(ignore_discard=True, ignore_expires=True)
109 
110  response = session.get(url, headers=self.stdHeader, verify=self.verify)
111 
112  if cookie_jar_path is not None:
113  session.cookies.save(ignore_discard=True, ignore_expires=True)
114 
115  return response, session
116 

◆ post_REST()

object generatetoken.RequestHelper.post_REST (   self,
str  function,
{str: str}   data = None 
)
Sends a POST request to the REST endpoint of the Moodle system
@param function: The Web service function to be called.
@param data: The optional data is added to the POST body.
@return: The JSON response returned by the Moodle system, already
checked for errors.

Definition at line 117 of file generatetoken.py.

117  def post_REST(self, function: str, data: {str: str} = None) -> object:
118  """
119  Sends a POST request to the REST endpoint of the Moodle system
120  @param function: The Web service function to be called.
121  @param data: The optional data is added to the POST body.
122  @return: The JSON response returned by the Moodle system, already
123  checked for errors.
124  """
125 
126  if self.token is None:
127  raise ValueError('The required Token is not set!')
128 
129  data_urlencoded = self._get_POST_DATA(function, self.token, data)
130  url = self._get_REST_POST_URL(self.url_base, function)
131 
132  response = requests.post(url, data=data_urlencoded, headers=self.stdHeader, verify=self.verify)
133  json_result = self._initial_parse(response)
134 
135  if self.log_responses and function not in ['tool_mobile_get_autologin_key']:
136  with open(self.log_responses_to, 'a') as response_log_file:
137  response_log_file.write('URL: {}\n'.format(response.url))
138  response_log_file.write('Function: {}\n\n'.format(function))
139  response_log_file.write('Data: {}\n\n'.format(data))
140  response_log_file.write(json.dumps(json_result, indent=4, ensure_ascii=False))
141  response_log_file.write('\n\n\n')
142 
143  return json_result
144 

◆ post_URL()

def generatetoken.RequestHelper.post_URL (   self,
str  url,
{str: str}   data = None,
str   cookie_jar_path = None 
)
Sends a POST request to a specific URL, including saving of cookies in cookie jar.
@param url: The url to which the request is sent. (the moodle base url is not added to the given URL)
@param data: The optional data is added to the POST body.
@param cookie_jar_path: Path to the cookies file.
@return: The resulting response object and the session object.

Definition at line 62 of file generatetoken.py.

62  def post_URL(self, url: str, data: {str: str} = None, cookie_jar_path: str = None):
63  """
64  Sends a POST request to a specific URL, including saving of cookies in cookie jar.
65  @param url: The url to which the request is sent. (the moodle base url is not added to the given URL)
66  @param data: The optional data is added to the POST body.
67  @param cookie_jar_path: Path to the cookies file.
68  @return: The resulting response object and the session object.
69  """
70 
71  data_urlencoded = ""
72  if data is not None:
73  data_urlencoded = RequestHelper.recursive_urlencode(data)
74 
75  session = requests.Session()
76 
77  if cookie_jar_path is not None:
78  session.cookies = MozillaCookieJar(cookie_jar_path)
79 
80  if os.path.exists(cookie_jar_path):
81  session.cookies.load(ignore_discard=True, ignore_expires=True)
82 
83  response = session.post(url, data=data_urlencoded, headers=self.stdHeader, verify=self.verify)
84 
85  if cookie_jar_path is not None:
86  for cookie in session.cookies:
87  cookie.expires = 2147483647
88 
89  session.cookies.save(ignore_discard=True, ignore_expires=True)
90 
91  return response, session
92 

◆ recursive_urlencode()

def generatetoken.RequestHelper.recursive_urlencode (   data)
static
URL-encode a multidimensional dictionary.
@param data: the data to be encoded
@returns: the url encoded data

Definition at line 275 of file generatetoken.py.

275  def recursive_urlencode(data):
276  """URL-encode a multidimensional dictionary.
277  @param data: the data to be encoded
278  @returns: the url encoded data
279  """
280 
281  def recursion(data, base=[]):
282  pairs = []
283 
284  for key, value in data.items():
285  new_base = base + [key]
286  if hasattr(value, 'values'):
287  pairs += recursion(value, new_base)
288  else:
289  new_pair = None
290  if len(new_base) > 1:
291  first = urllib.parse.quote(new_base.pop(0))
292  rest = map(lambda x: urllib.parse.quote(x), new_base)
293  new_pair = '%s[%s]=%s' % (first, ']['.join(rest), urllib.parse.quote(str(value)))
294  else:
295  new_pair = '%s=%s' % (urllib.parse.quote(str(key)), urllib.parse.quote(str(value)))
296  pairs.append(new_pair)
297  return pairs
298 
299  return '&'.join(recursion(data))
300 

Member Data Documentation

◆ stdHeader

dictionary generatetoken.RequestHelper.stdHeader
static
Initial value:
= {
'User-Agent': (
'Mozilla/5.0 (Linux; Android 7.1.1; Moto G Play Build/NPIS26.48-43-2; wv) AppleWebKit/537.36'
+ ' (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.99 Mobile Safari/537.36 MoodleMobile'
),
'Content-Type': 'application/x-www-form-urlencoded',
}

Definition at line 26 of file generatetoken.py.


The documentation for this class was generated from the following file: