def set(self, state): if state in "on off ccl": payload = {self.index: state.upper()} else: raise Exception("'{}' is not a valid state!".format(state)) utils.send_request(self.conf, "/outlet", payload)
def process_productivity(config, task): today = utils.send_request(config, perspective="interval", resolution_time="day", restrict_kind="efficiency") productivity_score = today.at[0, "Efficiency (percent)"] today = utils.send_request(config, perspective="interval", resolution_time="day", restrict_kind="productivity") very_productive_min = utils.extract_from_cell(today, 'Time', 'Productivity', 2) or 0 productive_min = utils.extract_from_cell(today, 'Time', 'Productivity', 1) or 0 time_remaining = task['minutes'] - (very_productive_min + productive_min) time_remaining = time_remaining if time_remaining > 0 else 0 utils.send_notification("You are %d percent productive so far!\n" \ "You have %d minutes out of %d minutes goal ahead of you." % (productivity_score, time_remaining, task['minutes']))
def get_events(start, end): params = {'start': start, 'end': end, 'pp': 100, 'page': 1} res = send_request(EVENTS_URL, params) events = res['events'] while res['page']['current'] < res['page']['total']: params['page'] += 1 res = send_request(EVENTS_URL, params) events += res['events'] # adjust response so that we can reuse the logic of create_table_by easily for event in events: for filter_name, filter_info in event['event']['filters'].items(): event['event'][filter_name] = filter_info return events
def config_update_is_required(nrds_url, nrds_token, nrds_config, nrds_config_version): """ Returns true or false based on value in the config_version variable in the config @todo Log results if we do not have this config """ get_args = { 'token': nrds_token, 'cmd': 'updatenrds', 'os': 'NCPA', 'configname': nrds_config, 'version': nrds_config_version } logging.debug('Connecting to NRDS server (%s)...', nrds_url) url_request = utils.send_request(nrds_url, **get_args) response_xml = ET.fromstring(url_request) status_xml = response_xml.findall('./status') if not status_xml: logging.warning("NRDS server did not respond with a status, skipping.") return False status = status_xml[0].text if status == "0": return False elif status == "1": return True else: logging.warning("Server does not have a record for %s config.", nrds_config) return False
def config_update_is_required(nrds_url, nrds_token, nrds_config, nrds_config_version): """ Returns true or false based on value in the config_version variable in the config @todo Log results if we do not have this config """ get_args = { 'token': nrds_token, 'cmd': 'updatenrds', 'os': 'NCPA', 'configname': nrds_config, 'version': nrds_config_version } logging.debug('Connecting to NRDS server (%s)...', nrds_url) url_request = utils.send_request(nrds_url, **get_args) response_xml = ET.fromstring(url_request) status_xml = response_xml.findall('./status') if not status_xml: logging.warning("NRDS server did not respond with a status, skipping.") return False status = status_xml[0].text if status == "0": return False elif status == "1": return True else: logging.warning("Server does not have a record for %s config.", nrds_config) return False
def main(): global output, events, file_name args = parse_arguments() output = os.environ['OUTPUT'] if 'OUTPUT' in os.environ else args.output start = os.environ['START'] if 'START' in os.environ else args.start start_date = datetime.strptime(start, '%Y-%m-%d') end = os.environ['END'] if 'END' in os.environ else args.end final_end_date = end_date = datetime.strptime(end, '%Y-%m-%d') days = (end_date - start_date).days file_name = 'osu-events-from-{}-to-{}'.format(start, end) events = [] while days > 365: end_date = start_date + timedelta(days=365) end = end_date.strftime('%Y-%m-%d') events += get_events(start, end) start_date = datetime.strptime(end, '%Y-%m-%d') + timedelta(days=1) start = start_date.strftime('%Y-%m-%d') end_date = final_end_date end = end_date.strftime('%Y-%m-%d') days = (end_date - start_date).days events += get_events(start, end) fields = [event_filter for event_filter in send_request(EVENT_FILTERS_URL).keys()] fields.append('departments') create_report_by(fields)
def authenticate(self, **kwargs): headers = {'content-type': 'application/x-www-form-urlencoded'} endpoint_url = self.__get_token_endpoint() data = None if self.redirect: if 'code' not in kwargs: raise AuthenticationFailed( "You first need to use the get_auth_uri() to get the 'code'" ) code = kwargs['code'] data = self.__get_token_using_code_params(code) else: data = self.__get_token_using_password_params() response = utils.send_request('POST', self.httplib, endpoint_url, headers, data=data) access_token = response['access_token'] instance_url = response['instance_url'] return Authentication(access_token, instance_url)
def categories(self): """Sends a GET request to the front page (app store base url), parses and returns a list of all available categories. Note: May contain some promotions, e.g. "Popular Characters" """ categories = {} strainer = SoupStrainer('a', {'class': 'child-submenu-link'}) response = send_request('GET', s.BASE_URL, params=self.params) soup = BeautifulSoup(response.content, 'lxml', from_encoding='utf8', parse_only=strainer) category_links = soup.select('a.child-submenu-link') age = '?age=' for cat in category_links: url = urljoin(s.BASE_URL, cat.attrs['href']) category_id = url.split('/')[-1] name = cat.string.strip() if age in category_id: category_id = 'FAMILY' url = url.split('?')[0] name = 'Family' if category_id not in categories: categories[category_id] = { 'name': name, 'url': url, 'category_id': category_id} return categories
def get_plugin(nrds_url, nrds_token, nrds_os, plugin_path, plugin): getargs = { 'cmd': 'getplugin', 'os': nrds_os, 'token': nrds_token, 'plugin': plugin } # This plugin_abs_path should be absolute, as it is adjusted when the daemon runs. url_request = utils.send_request(nrds_url, **getargs) plugin_abs_path = os.path.join(plugin_path, plugin) if plugin_abs_path != os.path.abspath(plugin_abs_path): raise ValueError( "Plugin path (%s) is not absolute, I will not continue safely.", plugin_abs_path) logging.debug("Downloading plugin to location: %s", plugin_abs_path) try: with open(plugin_abs_path, 'wb') as plugin_file: plugin_file.write(url_request) os.chmod(plugin_abs_path, 0775) except Exception as exc: logging.error('Could not write the plugin to %s: %r', plugin_abs_path, exc)
def abbyy(self, language_pair, text): if utils.is_single_word(text): logger.info('Перевод слова - используем Abbyy') target_language = get_abbyy_language_code(language_pair[0]) source_language = get_abbyy_language_code(language_pair[1]) url = ABBYY_BASIC_URL + '/Minicard' url_params = { 'text': text, 'srcLang': source_language, 'dstLang': target_language, } headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + config.ABBYY_API_TOKEN, } response = utils.send_request('GET', url, url_params, headers, '') if utils.is_response_not_ok(response): logger.warning(( 'Перевод с помощью ABBYY Lingvo не выполнен. ' + 'Для перевода будет использован Google.' )) return Translate.google(self, language_pair, text) return ParseTranslation.abbyy(self, response.text) else: logger.info('Перевод фразы/текста - используем Google') return Translate.google(self, language_pair, text)
def search(self, query, page=None, detailed=False): """Sends a POST request and retrieves a list of applications matching the query term(s). :param query: search query term(s) to retrieve matching apps :param page: the page number to retrieve. Max is 12. :param detailed: if True, sends request per app for its full detail :return: a list of apps matching search terms """ page = 0 if page is None else int(page) if page > len(self._pagtok) - 1: raise ValueError('Parameter \'page\' ({page}) must be between 0 and 12.'.format( page=page)) pagtok = self._pagtok[page] data = generate_post_data(0, 0, pagtok) self.params.update({ 'q': quote_plus(query), 'c': 'apps', }) response = send_request('POST', self._search_url, data, self.params) soup = BeautifulSoup(response.content, 'lxml', from_encoding='utf8') if detailed: apps = self._parse_multiple_apps(response) else: apps = [parse_card_info(app) for app in soup.select('div[data-uitype=500]')] return apps
def show(self): team_slug = self.options.get('<team_slug>', None) if team_slug: # show team submission info url = "{sprint_slug}/submission/{team_slug}/" response = send_request(url, sprint_slug=self.sprint_slug, team_slug=team_slug) else: # Show user team submission info url = "{sprint_slug}/submission/" response = send_request(url, sprint_slug=self.sprint_slug) if not response: return submission_data = response.json() print_submission_details(submission_data)
def __send_request(self, method, url, **kwargs): headers = utils.json_content_headers(self.auth.access_token) request_url = utils.get_request_url( url, self.auth.instance_url, self.url_resources.get_resource_url()) return utils.send_request(method, self.httplib, request_url, headers, **kwargs)
def __send_request(self, method, url, action, **kwargs): headers = utils.xml_content_headers(len(kwargs['data']), action) request_url = utils.get_request_url( url, self.auth.instance_url, self.url_resources.get_resource_url()) return utils.send_request(method, self.httplib, request_url, headers, **kwargs)
def get_weather(self): # get the location coordinates and sends a request to OWM api # returns a dic containing the weather data lat, lon = utils.get_location_coordinates(self.location) owmap_request = utils.make_owmap_request(lat, lon, self.part, self.units, self.api_key) weather = utils.send_request(owmap_request) utils.save_json_file(weather, self.res_file) return weather
def show(self): team_slug = self.options.get('<team_slug>', None) if team_slug: # show team submission info url = "{sprint_slug}/submission/{team_slug}/" response = send_request(url, sprint_slug=self.sprint_slug, team_slug=team_slug) else: # Show user team submission info url = "{sprint_slug}/submission/" response = send_request(url, sprint_slug=self.sprint_slug) if not response: return submission_data = response.json() print_submission_details(submission_data)
def __send_request(self, method, url, action, **kwargs): headers = utils.xml_content_headers(len(kwargs['data']), action) request_url = utils.get_request_url(url, self.auth.instance_url, self.url_resources.get_resource_url()) return utils.send_request(method, self.httplib, request_url, headers, **kwargs)
def __send_request(self, method, url, **kwargs): headers = utils.json_content_headers(self.auth.access_token) request_url = utils.get_request_url(url, self.auth.instance_url, self.url_resources.get_resource_url()) return utils.send_request(method, self.httplib, request_url, headers, **kwargs)
def proc_udp_request(self, req): self.client_associate = (req.dstaddr, req.dstport) self.last_clientaddr = self.client_associate self.client2local_udpsock = bind_local_udp(self.socksconn) self.local2remote_udpsock = bind_local_udp(self.remoteconn) if not self.client2local_udpsock or not self.local2remote_udpsock: request_fail(self.socksconn, req, GENERAL_SOCKS_SERVER_FAILURE) return False self.track_sock(self.client2local_udpsock) self.track_sock(self.local2remote_udpsock) send_request(self.remoteconn, UDP_ASSOCIATE, *sock_addr_info(self.local2remote_udpsock)) reply = read_reply(self.remoteconn) if reply.rep != SUCCEEDED: return False self.remote_associate = (reply.bndaddr, reply.bndport) request_success(self.socksconn, *sock_addr_info(self.client2local_udpsock)) return True
def connect(self): try: response_in_html = send_request(self.url) if not response_in_html: return None return parser(response_in_html, self.pool) except: traceback.print_exc() return None
def get_revision(self): """Returns a dictionary of 3 revision numbers""" soup = utils.send_request(self.conf, "/support.htm", None) ret = {} # FIXME: This is based on the assumption that the different # fields do not change order in other revisions.. table_lines = soup.find_all('td', width="70%") ret['firmware'] = table_lines[0].string.strip() ret['hardware'] = table_lines[1].string.strip() ret['serial'] = table_lines[3].string.strip() return ret
def collection(self, collection_id, category_id=None, results=None, page=None, age=None, detailed=False): """Sends a POST request and fetches a list of applications belonging to the collection and an optional category. :param collection_id: the collection id, e.g. 'NEW_FREE'. :param category_id: (optional) the category id, e.g. 'GAME_ACTION'. :param results: the number of apps to retrieve at a time. :param page: page number to retrieve; limitation: page * results <= 500. :param age: an age range to filter by (only for FAMILY categories) :param detailed: if True, sends request per app for its full detail :return: a list of app dictionaries """ if (collection_id not in COLLECTIONS and not collection_id.startswith('promotion')): raise ValueError('Invalid collection_id \'{collection}\'.'.format( collection=collection_id)) collection_name = COLLECTIONS.get(collection_id) or collection_id category = '' if category_id is None else CATEGORIES.get(category_id) if category is None: raise ValueError('Invalid category_id \'{category}\'.'.format( category=category_id)) results = s.NUM_RESULTS if results is None else results if results > 120: raise ValueError('Number of results cannot be more than 120.') page = 0 if page is None else page if page * results > 500: raise ValueError('Start (page * results) cannot be greater than 500.') if category.startswith('FAMILY') and age is not None: self.params['age'] = AGE_RANGE[age] url = build_collection_url(category, collection_name) data = generate_post_data(results, page) response = send_request('POST', url, data, self.params) if detailed: apps = self._parse_multiple_apps(response) else: soup = BeautifulSoup(response.content, 'lxml', from_encoding='utf8') apps = [parse_card_info(app_card) for app_card in soup.select('div[data-uitype=500]')] applist = [] for example in apps: for k,v in example.items(): if k == 'app_id': applist.append(v) return applist
def get_delays(self): """Returns a dictionary of delay settings. check "delay" section on your switch's admin page for more information.""" soup = utils.send_request(self.conf, "/admin.htm", None) delays = {} for i in range(9, 13): tmp = soup.find_all('tr', bgcolor="#F4F4F4")[i] delays[tmp.find_all('td')[0].string.replace(' ', '_')] = \ tmp.find_all('td')[1].find('input').get('value') return delays
def get_abbyy_api_token(): url = ABBYY_BASIC_URL + '/authenticate' headers = { 'Authorization': f'Basic {config.ABBYY_API_KEY}', } response = utils.send_request('POST', url, '', headers, '') if utils.is_response_not_ok(response): return errors.refresh_token_error return response.text.replace('"', '')
def get_rfc_from_peer(peer_ip, peer_port, rfc): utils.Logging.debug("Entering peer.get_rfc_from_peer") rfc_path = None try: sock = utils.send_request(peer_ip, peer_port, "GetRFC", {"rfc": rfc.number}) rfc_path, rfc_format = utils.accept_rfc(sock, rfc.number) if rfc_path: update_rfc_metadata(rfc.number, rfc.title, rfc_format) except BaseException as err: utils.Logging.info(err) utils.Logging.debug("Exiting peer.get_rfc_from_peer") return rfc_path
def get_rfc_index_from_peer(hostname, port): utils.Logging.debug("Entering peer.get_rfc_index_from_peer") peer_rfc_index_head = None try: sock = utils.send_request(hostname, port, "RFCQuery", {}) response = utils.accept_response(sock) if response.status == "200": peer_rfc_index_head = records.decode_rfc_list( hostname, response.data) except BaseException as err: utils.Logging.info(err) utils.Logging.debug("Exiting peer.get_rfc_index_from_peer") return peer_rfc_index_head
def explore_data(config): """Sends an API request and displays + plots the data""" # https://www.rescuetime.com/anapi/setup/documentation#analytic-api-reference data = utils.send_request(config, perspective="rank", # interval|rank (default) restrict_kind="overview", # overview|category|activity|document|efficiency|productivity resolution_time="day" # minute|hour|day|week|month (works only for perspective=interval) # if not restrict_time is provided, API returns log for the current day #restrict_begin='2018-09-20', #restrict_end='2018-09-20', #restrict_thing='Uncategorized' )
def authenticate(self): login_url = self.__get_token_endpoint() data = self.__get_params() headers = utils.xml_content_headers(len(data), "login") response = utils.send_request("POST", self.httplib, login_url, headers, data=data) xml_value = xml.dom.minidom.parseString(response.text) access_token = utils.get_element_by_name(xml_value, "sessionId") url = urlparse(utils.get_element_by_name(xml_value, "serverUrl")) instance_url = "{0}://{1}".format(url.scheme, url.netloc) return Authentication(access_token, instance_url)
def run(self): sprint_slug = get_slug() team_slug = self.options.get('<team_slug>', None) if team_slug: # show team info url = "{sprint_slug}/team/{team_slug}/" response = send_request(url, sprint_slug=sprint_slug, team_slug=team_slug) else: url = "{sprint_slug}/team/" response = send_request(url, sprint_slug=sprint_slug) # Show user team info if not response: return print response.json() data = response.json() message = data.get('message', '') log(message, msg_ctx={})
def get_latest_version(httplib): version_api_url = Version.VERSION_PATH latest_version = 0 response = utils.send_request('GET', httplib, version_api_url, None) for value in response: if float(value['version']) > latest_version: latest_version = float(value['version']) return latest_version
def forward_socks5_udp(self, url, localhandler, firstdata, firstaddr): remoteconn = socket.create_connection((url.hostname, url.port), self.timeout) remoteconn.settimeout(self.timeout) handler = SocksForwardSession(self.socksconn, remoteconn) # copy already-exist states from local handler handler.client_associate = localhandler.client_associate handler.last_clientaddr = localhandler.last_clientaddr handler.client2local_udpsock = localhandler.client2local_udpsock handler.track_sock(handler.client2local_udpsock) self.handler = handler # handshake, then request-reply, then send first packet, finally start to pipe if self.forward_socks5_handshake(handler.remoteconn): handler.local2remote_udpsock = utils.bind_local_udp(handler.remoteconn) handler.track_sock(handler.local2remote_udpsock) utils.send_request(handler.remoteconn, msg.UDP_ASSOCIATE, *utils.sock_addr_info(handler.local2remote_udpsock)) reply = utils.read_reply(handler.remoteconn) if reply.rep != msg.SUCCEEDED: return False handler.remote_associate = (reply.bndaddr, reply.bndport) handler.last_clientaddr = firstaddr handler.local2remote_udpsock.sendto(firstdata, handler.remote_associate) handler.relay_udp() return True
def __init__(self, conf): self.conf = conf self.name = "" self.outlets = [] # get data soup = utils.send_request(conf, "/index.htm", None) self.name = soup.find_all('th', bgcolor="#DDDDFF")[0].string.strip() for table_line in soup.find_all('tr', bgcolor="#F4F4F4"): self.outlets.append(outlet.Outlet( conf=self.conf, index=str(table_line.find_all('td')[0].string), name=str(table_line.find_all('td')[1].string), state=str(table_line.find_all('font')[0].string) ))
def google(self, text): url = GOOGLE_BASIC_URL + '/detect' url_params = ({'key': config.GOOGLE_API_KEY}) payload = ({ 'q': [text], }) headers = { 'Content-Type': 'application/json', } response = utils.send_request('POST', url, url_params, headers, payload) if utils.is_response_failed(response): return response return ParseLanguage.google(self, response.text)
def process_category(config, task): today = utils.send_request(config, perspective="rank", restrict_kind="overview") time_spent = utils.extract_from_cell(today, 'Time', 'Category', task['slice_name']) if time_spent: if config.doPlot: utils.plot_df(today, 'Category', 'Time') # send notification if task['task_type'] == 'limit': if time_spent > task['minutes']: utils.send_notification("Ooops you've spent %d minutes out of %d minutes limit on %s today." \ % (time_spent, task['minutes'], task['slice_name'])) elif task['task_type'] == 'goal': if time_spent < task['minutes']: utils.send_notification("Work harder! You have %d minutes out of %d minutes goal ahead of you to work on %s" \ % (task['minutes'] - time_spent, task['minutes'], task['slice_name']))
def revoke_token(self, access_token): # TODO: Fix, it seems is not working, don't know why # https://help.salesforce.com/apex/HTViewHelpDoc?id=remoteaccess_revoke_token.htm headers = {'content-type': 'application/x-www-form-urlencoded'} endpoint_url = self.__get_revoke_token_endpoint() # https://login.salesforce.com/services/oauth2/revoke?token=currenttokenID data = { 'token': urllib.quote(access_token) } response = utils.send_request('POST', self.httplib, endpoint_url, headers, data=data) return response
def push(self): submission_data = read_submission_meta_file(self.sprint_slug) files_data = submission_file_values(self.sprint_slug) url = "{sprint_slug}/submission/push/" response = send_request( url, sprint_slug=self.sprint_slug, data=submission_data, files=files_data) if not response: return msg = (response.json()['message']) msg_ctx = { 'line_color': BColors.OKGREEN, } log(msg, msg_ctx)
def authenticate(self): login_url = self.__get_token_endpoint() data = self.__get_params() headers = utils.xml_content_headers(len(data), 'login') response = utils.send_request('POST', self.httplib, login_url, headers, data=data) xml_value = xml.dom.minidom.parseString(response.text) access_token = utils.get_element_by_name(xml_value, 'sessionId') url = urlparse(utils.get_element_by_name(xml_value, 'serverUrl')) instance_url = '{0}://{1}'.format(url.scheme, url.netloc) return Authentication(access_token, instance_url)
def push(self): submission_data = read_submission_meta_file(self.sprint_slug) files_data = submission_file_values(self.sprint_slug) url = "{sprint_slug}/submission/push/" response = send_request(url, sprint_slug=self.sprint_slug, data=submission_data, files=files_data) if not response: return msg = (response.json()['message']) msg_ctx = { 'line_color': BColors.OKGREEN, } log(msg, msg_ctx)
def submit_to_nagios(self, checkresults): """ Submit the result as XML to the NRDP server. :param checkresults: The XML that will be submitted back to Nagios. :type checkresults: xml.dom.minidom.Document :rtype: None """ server = self.config.get('nrdp', 'parent') token = self.config.get('nrdp', 'token') # The POST requests don't follow redirects, so we have to make sure # the address is completely accurate. if not server.endswith('/'): server += '/' logging.debug('XML to be submitted: %s', checkresults) ret_xml = utils.send_request(url=server, token=token, XMLDATA=checkresults, cmd='submitcheck') Handler.log_result(ret_xml)
def yandex(self, text): url = YANDEX_BASIC_URL + '/detect' payload = ({ 'folder_id': config.YANDEX_FOLDER_ID, 'languageCodeHints': ['ru', 'en'], 'text': text, }) headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {config.YANDEX_API_TOKEN}', } response = utils.send_request('POST', url, '', headers, payload) if utils.is_response_failed(response): return response return ParseLanguage.yandex(self, response.text)
def yandex(self, language_pair, text): url = YANDEX_BASIC_URL + '/translate' payload = ({ 'folder_id': config.YANDEX_FOLDER_ID, 'texts': [text], 'targetLanguageCode': language_pair[0], 'sourceLanguageCode': language_pair[1], }) headers = { 'Content-Type': 'application/json', 'Authorization': f'Api-Key {config.YANDEX_API_TOKEN}', } response = utils.send_request('POST', url, '', headers, payload) if utils.is_response_failed(response): return response return ParseTranslation.yandex(self, response.text)
def run(self): sprint_slug = self.options.get('<sprint_slug>', None) if not sprint_slug: log("Enter the hackathon slug to access the hackathon.", {'line_color': BColors.WARNING}) return url = "{sprint_slug}/access/" response = send_request(url, sprint_slug=sprint_slug) if not response: return msg = ("Access set to {sprint_slug}.\n") msg_ctx = {'line_color': BColors.OKBLUE, 'sprint_slug': sprint_slug} log(msg, msg_ctx) print_sprint_details(response.json())
def authenticate(self, **kwargs): headers = {"content-type": "application/x-www-form-urlencoded"} endpoint_url = self.__get_token_endpoint() data = None if self.redirect: if "code" not in kwargs: raise AuthenticationFailed("You first need to use the get_auth_uri() to get the 'code'") code = kwargs["code"] data = self.__get_token_using_code_params(code) else: data = self.__get_token_using_password_params() response = utils.send_request("POST", self.httplib, endpoint_url, headers, data=data) access_token = response["access_token"] instance_url = response["instance_url"] return Authentication(access_token, instance_url)
def submit_to_nagios(self, checkresults): """ Submit the result as XML to the NRDP server. :param checkresults: The XML that will be submitted back to Nagios. :type checkresults: xml.dom.minidom.Document :rtype: None """ try: server = self.config.get('nrdp', 'parent') token = self.config.get('nrdp', 'token') except Exception as ex: logging.exception(ex) # Get the list of servers (and tokens, if available) servers = server.split(',') tokens = token.split(',') for i, server in enumerate(servers): # Grab a token, or the last token try: tmp_token = tokens[i] token = tmp_token except IndexError: pass # The POST requests don't follow redirects, so we have to make sure # the address is completely accurate. if not server.endswith('/'): server += '/' logging.debug('XML to be submitted: %s', checkresults) ret_xml = utils.send_request(url=server, token=token, XMLDATA=checkresults, cmd='submitcheck') try: Handler.log_result(ret_xml) except Exception as ex: logging.debug(ret_xml) logging.exception(ex)
def update_config(self, nrds_url, nrds_token, nrds_config): """ Downloads new config to whatever is declared as path @todo Validate config before saving """ get_args = { 'configname': nrds_config, 'cmd': 'getconfig', 'os': 'NCPA', 'token': nrds_token } nrds_response = utils.send_request(nrds_url, **get_args) try: with tempfile.TemporaryFile() as temp_config: temp_config = tempfile.TemporaryFile() temp_config.write(nrds_response) temp_config.seek(0) test_config = ConfigParser.ConfigParser() test_config.readfp(temp_config) if not test_config.sections(): raise Exception('Config contained no NCPA directives, not writing.') except Exception as exc: logging.error("NRDS config recieved from the server contained errors: %r", exc) return False if nrds_response: try: with open(self.config.file_path, 'wb') as new_config: new_config.write(nrds_response) except Exception as exc: logging.error('Could not rewrite the config: %r', exc) return False else: logging.info('Successfully updated NRDS config.') return True
def run(self): sprint_slug = self.options.get('<sprint_slug>', None) if not sprint_slug: log("Enter the hackathon slug to access the hackathon.", {'line_color': BColors.WARNING}) return url = "{sprint_slug}/access/" response = send_request(url, sprint_slug=sprint_slug) if not response: return msg = ("Access set to {sprint_slug}.\n") msg_ctx = { 'line_color': BColors.OKBLUE, 'sprint_slug': sprint_slug } log(msg, msg_ctx) print_sprint_details(response.json())
def get_plugin(nrds_url, nrds_token, nrds_os, plugin_path, plugin): getargs = { 'cmd': 'getplugin', 'os': nrds_os, 'token': nrds_token, 'plugin': plugin } # This plugin_abs_path should be absolute, as it is adjusted when the daemon runs. url_request = utils.send_request(nrds_url, **getargs) plugin_abs_path = os.path.join(plugin_path, plugin) if plugin_abs_path != os.path.abspath(plugin_abs_path): raise ValueError("Plugin path (%s) is not absolute, I will not continue safely.", plugin_abs_path) logging.debug("Downloading plugin to location: %s", plugin_abs_path) try: with open(plugin_abs_path, 'wb') as plugin_file: plugin_file.write(url_request) os.chmod(plugin_abs_path, 0775) except Exception as exc: logging.error('Could not write the plugin to %s: %r', plugin_abs_path, exc)
def authenticate(self, **kwargs): headers = {'content-type': 'application/x-www-form-urlencoded'} endpoint_url = self.__get_token_endpoint() data = None # In some scenarios maybe is interesting to just inject the access_token and try to execute the # petition, adding the logic on the request to catch the RESPONSE_CODE_EXPIRED_SESSION Exception # and in case that a refresh token is provided, refresh the token and execute the action again # # if 'access_token' in kwargs: # if refresh_token' in kwargs: # return Authentication(kwargs['access_token'], instance_url, kwargs['refresh_token']) # else: # return Authentication(kwargs['access_token'], instance_url) if 'refresh_token' in kwargs: data = self.__get_token_using_refresh_token_params(kwargs['refresh_token']) else: if self.redirect: if 'code' not in kwargs: raise AuthenticationFailed("You first need to use the get_auth_uri() to get the 'code'") data = self.__get_token_using_code_params(kwargs['code']) else: data = self.__get_token_using_password_params() response = utils.send_request('POST', self.httplib, endpoint_url, headers, data=data) refresh_token = '' if 'refresh_token' in response: refresh_token = response['refresh_token'] access_token = response['access_token'] instance_url = response['instance_url'] return Authentication(access_token, instance_url, refresh_token)
def rename(self, name=None): if not name or name == "": name = "Outlet " + str(self.index) payload = {'outname' + str(self.index): name} utils.send_request(self.conf, "/unitnames.cgi?data", payload)
def make_response(self, request, queryset): for item in queryset: send_request(item.id)
def rename(self, name): payload = {'ctrlname' : name} utils.send_request(self.conf, "/unitnames.cgi?data", payload)