moodleNotifer

Public Member Functions | Static Public Member Functions | Public Attributes | Static Public Attributes | List of all members
main.letsloginourself.RequestHelper Class Reference

This is Class for Creating and formatting requests made to Moodle API functions. 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 is Class for Creating and formatting requests made to Moodle API functions.

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

Definition at line 18 of file letsloginourself.py.

## Member Function Documentation

## ◆ get_login()

object main.letsloginourself.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 170 of file letsloginourself.py.

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

## ◆ get_simple_moodle_version()

float main.letsloginourself.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 200 of file letsloginourself.py.

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

## ◆ get_URL()

def main.letsloginourself.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 91 of file letsloginourself.py.

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

## ◆ post_REST()

object main.letsloginourself.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 115 of file letsloginourself.py.

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

## ◆ post_URL()

def main.letsloginourself.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 60 of file letsloginourself.py.

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

## ◆ recursive_urlencode()

def main.letsloginourself.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 273 of file letsloginourself.py.

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

## Member Data Documentation

## ◆ stdHeader

dictionary main.letsloginourself.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 24 of file letsloginourself.py.

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

- main/letsloginourself.py