def _request(self, method, params=None, use_login_repeat=None): if not isinstance(method, unicode_string): method = method.decode('ascii') if use_login_repeat is None: use_login_repeat = (method not in ('logout', 'authenticate')) attempts_left = self.config['login_repeat'] if use_login_repeat else 0 data = None while data is None: try: data = rpc_request(self.config, method, params or {}) except errors.NotLoggedInError: if attempts_left > 0: self.logout(suppress_errors=True) self.login() else: raise errors.NotLoggedInError( 'Tried to login several times, failed. Original method' ' was ' + method) else: return data attempts_left -= 1 # new round!
def rpc_request(config, method, params): ''' A method for sending a JSON-RPC request. :param config: A dictionary containing ``useragent``, ``server``, ``school``, ``username`` and ``password`` :type config: dict :param method: The JSON-RPC method to be executed :type method: str :param params: JSON-RPC parameters to the method (should be JSON serializable) :type params: dict ''' server = config['server'] school = config['school'] useragent = config['useragent'] assert isinstance(method, unicode_string) assert isinstance(server, unicode_string) assert isinstance(school, unicode_string) assert isinstance(useragent, unicode_string) for v in params.values(): assert not isinstance(v, bytestring) url = server + u'?school=' + school headers = {u'User-Agent': useragent, u'Content-Type': u'application/json'} request_body = { u'id': str(datetime.datetime.today()), u'method': method, u'params': params, u'jsonrpc': u'2.0' } if method != u'authenticate': if 'jsessionid' in config: assert isinstance(config['jsessionid'], unicode_string) headers['Cookie'] = u'JSESSIONID=' + config['jsessionid'] else: raise errors.NotLoggedInError( 'Don\'t have JSESSIONID. Did you already log out?') log('debug', 'Making new request:') log('debug', 'URL: ' + url) if method != u'authenticate': # user credentials will not be logged - fixing #14 log('debug', 'DATA: ' + str(request_body)) if '_http_session' not in config: config['_http_session'] = requests.session() http_session = config['_http_session'] result_body = _send_request(url, request_body, headers, http_session) return _parse_result(request_body, result_body)
def throw_errors(): if not suppress_errors: raise errors.NotLoggedInError('We already were logged out.')