code
stringlengths
1
18.2k
auth,url) delete_ip_address_url = '''/imcrs/res/access/assignedIpScope/'''+str(scope_id) f_url = url + delete_ip_address_url r = requests.delete(f_url, auth=auth, headers=HEADERS) try: return r if r.status_code == 204: #print("IP Segment Successfully Deleted") return r.status_code except requests.exceptions.RequestExce...
def add_scope_ip(ipaddress, name, description, scopeid, auth, url): """ Function to add new host IP address allocation to existing scope ID :param ipaddress: :param name: name of the owner of this host :param description: Description of the host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.a...
import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> add_scope_ip('10.50.0.5', 'cyoung', 'New Test Host','175', auth.creds, auth.url) """ new_ip = { "ip": ipaddress, "name": name, "description": description} add_scope_ip_url = '/imcrs/res/access...
== 200: #print("IP Scope Successfully Created") return r.status_code elif r.status_code == 409: #print("IP Scope Already Exists") return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " add_ip_scope: An Error has occured"
def remove_scope_ip(hostid, auth, url): """ Function to add remove IP address allocation :param hostid: Host id of the host to be deleted :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: S...
pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> add_host_to_segment('10.50.0.5', 'cyoung', 'New Test Host', '10.50.0.0/24', auth.creds, auth.url) >>> host_...
requests.delete(f_url, auth=auth, headers=HEADERS, ) try: if r.status_code == 204: #print("Host Successfully Deleted") return r.status_code elif r.status_code == 409: #print("IP Scope Already Exists") return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " add_ip_scope: An ...
def get_ip_scope_hosts( scopeId, auth, url): """ Function requires input of scope ID and returns list of allocated IP address for the specified scope :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclas...
represents a single host assigned to the IP scope :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> scope_id = get_scope_id('10.50.0.0/24', auth.creds, auth.url) >>> ip_scope_hosts = get_ip_scope_hosts(scop...
in ip_scope_hosts[0] """ get_ip_scope_url = "/imcrs/res/access/assignedIpScope/ip?size=10000&ipScopeId="+str(scopeId) f_url = url + get_ip_scope_url r = requests.get(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 200: ipscopelist = (json.loads(r....
str(e) + " get_ip_scope: An Error has occured"
def add_host_to_segment(ipaddress, name, description, network_address, auth, url): ''' Function to abstract existing add_scope_ip_function. Allows for use of network address rather than forcing human to learn the scope_id :param ipaddress: :param name: name of the owner of this host :param description: Description of t...
the length of the subnet mask. Example: 10.50.0.0 255.255.255.0 would be written as 10.50.0.0/24 :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: :rtype: ''' scope_id = get_scope_id(networ...
def delete_host_from_segment(ipaddress, networkaddress, auth, url): '''Function to abstract ''' host_id = get_host_id(ipaddress, networkaddress, auth, url) remove_scope_ip(host_id, auth.creds, auth.url)
def generate_signature(method, version, endpoint, date, rel_url, content_type, content, access_key, secret_key, hash_type): ''' Generates the API request signature from the given parameters. ''' hash_type = hash_type hostname = endpoint._val.netloc # FIXME: migrate to public API if version >= 'v4.20181215': content = b...
sign_bytes = sign_str.encode() sign_key = hmac.new(secret_key.encode(), date.strftime('%Y%m%d').encode(), hash_type).digest() sign_key = hmac.new(sign_key, hostname.encode(), hash_type).digest() signature = hmac.new(sign_key, sign_bytes, hash_type).hexdigest() headers = { 'Authorization': 'BackendAI signMethod=HMAC-{},...
async def list_with_limit(cls, limit, offset, status: str = 'ALIVE', fields: Iterable[str] = None) -> Sequence[dict]: ''' Fetches the list of agents with the given status with limit and offset for pagination. :param limit: number of agents to get :param offset: offset index of agents to get :param status: An upper-case...
per-agent query fields to fetch. ''' if fields is None: fields = ( 'id', 'addr', 'status', 'first_contact', 'mem_slots', 'cpu_slots', 'gpu_slots', ) q = 'query($limit: Int!, $offset: Int!, $status: String) {' \ ' agent_list(limit: $limit, offset: $offset, status: $status) {' \ ' items { $fields }' \ ' total_count' \ ' ...
offset, 'status': status, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['agent_list']
def set_content(self, value: RequestContent, *, content_type: str = None): ''' Sets the content of the request. ''' assert self._attached_files is None, \ 'cannot set content because you already attached files.' guessed_content_type = 'application/octet-stream' if value is None: guessed_content_type = 'text/plain' self...
is not None else guessed_content_type)
def set_json(self, value: object): ''' A shortcut for set_content() with JSON objects. ''' self.set_content(modjson.dumps(value, cls=ExtendedJSONEncoder), content_type='application/json')
def attach_files(self, files: Sequence[AttachedFile]): ''' Attach a list of files represented as AttachedFile. ''' assert not self._content, 'content must be empty to attach files.' self.content_type = 'multipart/form-data' self._attached_files = files
def _sign(self, rel_url, access_key=None, secret_key=None, hash_type=None): ''' Calculates the signature of the given request and adds the Authorization HTTP header. It should be called at the very end of request preparation and before sending the request to the server. ''' if access_key is None: access_key = self.conf...
generate_signature( self.method, self.config.version, self.config.endpoint, self.date, str(rel_url), self.content_type, self._content, access_key, secret_key, hash_type) self.headers.update(hdrs)
def fetch(self, **kwargs) -> 'FetchContextManager': ''' Sends the request to the server and reads the response. You may use this method either with plain synchronous Session or AsyncSession. Both the followings patterns are valid: .. code-block:: python3 from ai.backend.client.request import Request from ai.backend.cli...
import Request from ai.backend.client.session import AsyncSession async with AsyncSession() as sess: rqst = Request(sess, 'GET', ...) async with rqst.fetch() as resp: print(await resp.text()) ''' assert self.method in self._allowed_methods, \ 'Disallowed HTTP method: {}'.format(self.method) self.date = datetime.now(tzu...
def connect_websocket(self, **kwargs) -> 'WebSocketContextManager': ''' Creates a WebSocket connection. .. warning:: This method only works with :class:`~ai.backend.client.session.AsyncSession`. ''' assert isinstance(self.session, AsyncSession), \ 'Cannot use websockets with sessions in the synchronous mode' assert sel...
heartbeat=30.0, headers=self.headers) return WebSocketContextManager(self.session, ws_ctx, **kwargs)
def main(): """ Main function. :return: None. """ try: # Get the `src` directory's absolute path src_path = os.path.dirname( # `aoiklivereload` directory's absolute path os.path.dirname( # `demo` directory's absolute path os.path.dirname( # This file's absolute path os.path.abspath(__file__) ) ) ) # If the `src` direct...
save user setting PYTHONPATH when running this demo. # sys.path.append(src_path) # Import reloader class from aoiklivereload import LiveReloader # Create reloader reloader = LiveReloader( # Reload mode. # # In windows, have to use `spawn_exit` reload mode and force the # current process to exit immediately, otherwise w...
address # (protocol/network address/port) is normally permitted # ``` # # Notice in `spawn_exit` reload mode, the user will not be able # to kill the new process using Ctrl-c. # reload_mode=('spawn_exit' if sys.platform == 'win32' else 'exec'), force_exit=True, ) # Start watcher thread reloader.start_watcher_thread() #...
Run server -----\nHost: {}\nPort: {}'.format( server_host, server_port ) # Print message print(msg) # Create request handler class HelloHandler(tornado.web.RequestHandler): """ Request handler class. """ def get(self): """ Request handler. :return: None. """ # Write response body self.write('hello') # List of tuples th...
debug=False, ) # Start listening tornado_app.listen(server_port, address=server_host) # Get event loop io_loop = tornado.ioloop.IOLoop.current() # Run event loop io_loop.start() # If have `KeyboardInterrupt` except KeyboardInterrupt: # Not treat as error pass
def add_perf_task(task, auth, url): """ function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into JSON and issues a RESTFUL call to create the performance task. device. :param task: dictionary containing all required fields for performance tasks :param auth: requ...
auth.url from pyhpeimc.auth.authclass :return: 204 :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_task = {'indexDesc': '1.3.6.1.4.1.9.9.13.1.3.1.3', 'indexType': '[index1[0]:ciscoEnvMonTemperatureStatusValu...
try: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' add_perf_task: An Error has occured'
def get_perf_task(task_name, auth, url): """ function takes the a str object containing the name of an existing performance tasks and issues a RESTFUL call to the IMC REST service. It will return a list :param task_name: str containing the name of the performance task :param auth: requests auth object #usually auth.cre...
from pyhpeimc.auth.authclass :return: 204 :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.perf import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> selected_task = get_perf_task('Cisco_Temperature', auth.creds, auth.url) >>> assert type(selected_task) is dict >>> asse...
= (json.loads(response.text)) if 'task' in perf_task_info: perf_task_info = (json.loads(response.text))['task'] else: perf_task_info = "Task Doesn't Exist" return perf_task_info except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_perf_task: An Error has occured'
def delete_perf_task(task_name, auth, url): """ Function takes a str of the target task_name to be deleted and retrieves task_id using the get_perf_task function. Once the task_id has been successfully retrieved it is populated into the task_id variable and an DELETE call is made against the HPE IMC REST interface to d...
object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: int of 204 if successful, str of "Perf Task doesn't exist" i :rtype: int """ task_id = get_perf_task(task_name, auth, url) if isinstance(task_id, str): print("Perf ta...
auth=auth, headers=HEADERS) try: if response.status_code == 204: print("Perf Task successfully delete") return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' delete_perf_task: An Error has occured'
def process_json_response(self, response): """For a json response, check if there was any error and throw exception. Otherwise, create a housecanary.response.Response.""" response_json = response.json() # handle errors code_key = "code" if code_key in response_json and response_json[code_key] != constants.HTTP_CODE_OK:...
if code == constants.HTTP_TOO_MANY_REQUESTS: raise housecanary.exceptions.RateLimitException(code, message, response) else: raise housecanary.exceptions.RequestException(code, message) request_url = response.request.url endpoint_name = self._parse_endpoint_name_from_url(request_url) return Response.create(endpoint_name...
def start_watcher_thread(self): """ Start watcher thread. :return: Watcher thread object. """ # Create watcher thread watcher_thread = threading.Thread(target=self.run_watcher) # If the reload mode is `spawn_wait` if self._reload_mode == self.RELOAD_MODE_V_SPAWN_WAIT: # Use non-daemon thread daemon = False # If the rel...
watcher_thread.start() # Return watcher thread return watcher_thread
def run_watcher(self): """ Watcher thread's function. :return: None. """ # Create observer observer = Observer() # Start observer observer.start() # Dict that maps file path to `watch object` watche_obj_map = {} # Run change check in a loop while not self._watcher_to_stop: # Get current watch paths old_watch_path_s = s...
new_watch_path in new_watch_path_s: # Remove from the old watch paths if exists old_watch_path_s.discard(new_watch_path) # If the new watch path was not watched if new_watch_path not in watche_obj_map: try: # Schedule a watch watch_obj = observer.schedule( # 2KGRW # `FileSystemEventHandler` instance self, # File path t...
except OSError: # Set the watch object be None watche_obj_map[new_watch_path] = None # For each old watch path that is not in the new watch paths for old_watch_path in old_watch_path_s: # Get watch object watch_obj = watche_obj_map.pop(old_watch_path, None) # If have watch object if watch_obj is not None: # Unschedule ...
next check time.sleep(self._interval)
def _find_watch_paths(self): """ Find paths to watch. :return: Paths to watch. """ # Add directory paths in `sys.path` to watch paths watch_path_s = set(os.path.abspath(x) for x in sys.path) # For each extra path for extra_path in self._extra_paths or (): # Get the extra path's directory path extra_dir_path = os.path.d...
list(sys.modules.values()): # Get module file path module_path = getattr(module, '__file__', None) # If have module file path if module_path is not None: # Get module directory path module_dir_path = os.path.dirname(os.path.abspath(module_path)) # Add to watch paths watch_path_s.add(module_dir_path) # Find short paths ...
watch_path_s
def _find_short_paths(self, paths): """ Find short paths of given paths. E.g. if both `/home` and `/home/aoik` exist, only keep `/home`. :param paths: Paths. :return: Set of short paths. """ # Split each path to parts. # E.g. '/home/aoik' to ['', 'home', 'aoik'] path_parts_s = [path.split(os.path.sep) for path in paths...
longest being the first. # # Longer paths appear first so that their extra parts are discarded # when a shorter path is found at 5TQ8L. # # Then for each path's parts. for parts in sorted(path_parts_s, key=len, reverse=True): # Start from the root node node = root_node # For each part of the path for part in parts: # C...
path node = node.setdefault(part, {}) # 5TQ8L # Clear the last path part's node's child nodes. # # This aims to keep only the shortest path that needs be watched. # node.clear() # Short paths short_path_s = set() # Collect leaf paths self._collect_leaf_paths( node=root_node, path_parts=(), leaf_paths=short_path_s, ) # ...
def _collect_leaf_paths(self, node, path_parts, leaf_paths): """ Collect paths of leaf nodes. :param node: Starting node. Type is dict. Key is child node's path part. Value is child node. :param path_parts: The starting node's path parts. Type is tuple. :param leaf_paths: Leaf path list. :return: None. """ # If the nod...
Add to list leaf_paths.add(node_path) # If the node is not leaf node else: # For each child node for child_path_part, child_node in node.items(): # Get the child node's path parts child_path_part_s = path_parts + (child_path_part,) # Visit the child node self._collect_leaf_paths( node=child_node, path_parts=child_path_...
def dispatch(self, event): """ Dispatch file system event. Callback called when there is a file system event. Hooked at 2KGRW. This function overrides `FileSystemEventHandler.dispatch`. :param event: File system event object. :return: None. """ # Get file path file_path = event.src_path # If the file path is in extra p...
`.pyc` or `.pyo` if file_path.endswith(('.pyc', '.pyo')): # Get `.py` file path file_path = file_path[:-1] # If the file path ends with `.py` if file_path.endswith('.py'): # Get the file's directory path file_dir = os.path.dirname(file_path) # If the file's directory path starts with any of the watch paths if file_dir....
def reload(self): """ Reload the program. :return: None. """ # Get reload mode reload_mode = self._reload_mode # If reload mode is `exec` if self._reload_mode == self.RELOAD_MODE_V_EXEC: # Call `reload_using_exec` self.reload_using_exec() # If reload mode is `spawn_exit` elif self._reload_mode == self.RELOAD_MODE_V_SPA...
of above else: # Get error message error_msg = 'Invalid reload mode: {}.'.format(repr(reload_mode)) # Raise error raise ValueError(error_msg)
def reload_using_exec(self): """ Reload the program process. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Reload the program process os.execvpe( # Program file path sys.executable, # Command parts cmd_parts, # Env dict env_copy, )
def reload_using_spawn_exit(self): """ Spawn a subprocess and exit the current process. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Spawn subprocess subprocess.Popen(cmd_parts, env=env_copy, close_fds=True) # If need force exit if ...
interrupt_main() # Set the flag self._watcher_to_stop = True # Exit the watcher thread sys.exit(0)
def reload_using_spawn_wait(self): """ Spawn a subprocess and wait until it finishes. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Send interrupt to main thread interrupt_main() # Spawn subprocess and wait until it finishes subproce...
def agent(agent_id): ''' Show the information about the given agent. ''' fields = [ ('ID', 'id'), ('Status', 'status'), ('Region', 'region'), ('First Contact', 'first_contact'), ('CPU Usage (%)', 'cpu_cur_pct'), ('Used Memory (MiB)', 'mem_cur_bytes'), ('Total slots', 'available_slots'), ('Occupied slots', 'occupied_slo...
fields)) v = {'agent_id': agent_id} with Session() as session: try: resp = session.Admin.query(q, v) except Exception as e: print_error(e) sys.exit(1) info = resp['agent'] rows = [] for name, key in fields: if key == 'mem_cur_bytes' and info[key] is not None: info[key] = round(info[key] / 2 ** 20, 1) if key in info: ro...
def agents(status, all): ''' List and manage agents. (admin privilege required) ''' fields = [ ('ID', 'id'), ('Status', 'status'), ('Region', 'region'), ('First Contact', 'first_contact'), ('CPU Usage (%)', 'cpu_cur_pct'), ('Used Memory (MiB)', 'mem_cur_bytes'), ('Total slots', 'available_slots'), ('Occupied slots', 'o...
print_error(e) sys.exit(1) return resp_agents def round_mem(results): for item in results: if 'mem_cur_bytes' in item and item['mem_cur_bytes'] is not None: item['mem_cur_bytes'] = round(item['mem_cur_bytes'] / 2 ** 20, 1) return results def _generate_paginated_results(interval): offset = 0 is_first = True total_count ...
+= interval total_count = result['total_count'] items = result['items'] items = round_mem(items) table = tabulate((item.values() for item in items), headers=(item[0] for item in fields)) if is_first: is_first = False else: table_rows = table.split('\n') table = '\n'.join(table_rows[2:]) yield table + '\n' if not offset...
total_count == 0: print('There are no matching agents.') return items = result['items'] items = round_mem(items) fields = [field for field in fields if field[1] in items[0]] print(tabulate((item.values() for item in items), headers=(item[0] for item in fields))) if total_count > paginating_interval: print("More agents ...
def resource_policy(name): """ Show details about a keypair resource policy. When `name` option is omitted, the resource policy for the current access_key will be returned. """ fields = [ ('Name', 'name'), ('Created At', 'created_at'), ('Default for Unspecified', 'default_for_unspecified'), ('Total Resource Slot', 'tot...
Hosts', 'allowed_vfolder_hosts'), ] with Session() as session: try: rp = session.ResourcePolicy(session.config.access_key) info = rp.info(name, fields=(item[1] for item in fields)) except Exception as e: print_error(e) sys.exit(1) rows = [] if info is None: print('No such resource policy.') sys.exit(1) for name, key in...
def resource_policies(ctx): ''' List and manage resource policies. (admin privilege required) ''' if ctx.invoked_subcommand is not None: return fields = [ ('Name', 'name'), ('Created At', 'created_at'), ('Default for Unspecified', 'default_for_unspecified'), ('Total Resource Slot', 'total_resource_slots'), ('Max Concur...
items = session.ResourcePolicy.list(fields=(item[1] for item in fields)) except Exception as e: print_error(e) sys.exit(1) if len(items) == 0: print('There are no keypair resource policies.') return print(tabulate((item.values() for item in items), headers=(item[0] for item in fields)))
def add(name, default_for_unspecified, total_resource_slots, max_concurrent_sessions, max_containers_per_session, max_vfolder_count, max_vfolder_size, idle_timeout, allowed_vfolder_hosts): ''' Add a new keypair resource policy. NAME: NAME of a new keypair resource policy. ''' with Session() as session: try: data = sess...
data['resource_policy'] print('Keypair resource policy ' + item['name'] + ' is created.')
def delete(name): """ Delete a keypair resource policy. NAME: NAME of a keypair resource policy to delete. """ with Session() as session: if input('Are you sure? (y/n): ').lower().strip()[:1] != 'y': print('Canceled.') sys.exit(1) try: data = session.ResourcePolicy.delete(name) except Exception as e: print_error(e) sys...
def app(session_id, app, bind, port): """ Run a local proxy to a service provided by Backend.AI compute sessions. The type of proxy depends on the app definition: plain TCP or HTTP. \b SESSID: The compute session ID. APP: The name of service provided by the given session. """ api_session = None runner = None async def ...
= AsyncSession() # TODO: generalize protocol using service ports metadata protocol = 'http' runner = ProxyRunner(api_session, session_id, app, protocol, bind, port, loop=loop) await runner.ready() print_info( "A local proxy to the application \"{0}\" ".format(app) + "provided by the session \"{0}\" ".format(session_id)...
to \"{}\" has terminated." .format(app)) asyncio_run_forever(app_setup(), app_shutdown(), stop_signals={signal.SIGINT, signal.SIGTERM})
def get_env(key: str, default: Any = None, clean: Callable[[str], Any] = lambda v: v): ''' Retrieves a configuration value from the environment variables. The given *key* is uppercased and prefixed by ``"BACKEND_"`` and then ``"SORNA_"`` if the former does not exist. :param key: The key name. :param default: The defaul...
that is applied to the result of lookup (in both successes and the default value for failures). The default is returning the value as-is. :returns: The value processed by the *clean* function. ''' key = key.upper() v = os.environ.get('BACKEND_' + key) if v is None: v = os.environ.get('SORNA_' + key) if v is None: if de...
clean(v)
def logs(sess_id_or_alias): ''' Shows the output logs of a running container. \b SESSID: Session ID or its alias given when creating the session. ''' with Session() as session: try: print_wait('Retrieving container logs...') kernel = session.Kernel(sess_id_or_alias) result = kernel.get_logs().get('result') logs = resul...
def _wrap_key(function, args, kws): ''' get the key from the function input. ''' return hashlib.md5(pickle.dumps((_from_file(function) + function.__name__, args, kws))).hexdigest()
def get(key, adapter = MemoryAdapter): ''' get the cache value ''' try: return pickle.loads(adapter().get(key)) except CacheExpiredException: return None
def set(key, value, timeout = -1, adapter = MemoryAdapter): ''' set cache by code, must set timeout length ''' if adapter(timeout = timeout).set(key, pickle.dumps(value)): return value else: return None
def wrapcache(timeout = -1, adapter = MemoryAdapter): ''' the Decorator to cache Function. ''' def _wrapcache(function): @wraps(function) def __wrapcache(*args, **kws): hash_key = _wrap_key(function, args, kws) try: adapter_instance = adapter() return pickle.loads(adapter_instance.get(hash_key)) except CacheExpiredExce...
def export_analytics_data_to_excel(data, output_file_name, result_info_key, identifier_keys): """Creates an Excel file containing data returned by the Analytics API Args: data: Analytics API data as a list of dicts output_file_name: File name for output Excel file (use .xlsx extension). """ workbook = create_excel_work...
def export_analytics_data_to_csv(data, output_folder, result_info_key, identifier_keys): """Creates CSV files containing data returned by the Analytics API. Creates one file per requested endpoint and saves it into the specified output_folder Args: data: Analytics API data as a list of dicts output_folder: Path to a fo...
in workbook.worksheets: file_name = utilities.convert_title_to_snake_case(worksheet.title) file_path = os.path.join(output_folder, file_name + suffix) mode = 'w' if sys.version_info[0] < 3: mode = 'wb' with io.open(file_path, mode) as output_file: csv_writer = csv.writer(output_file) for row in worksheet.rows: csv_writ...
def concat_excel_reports(addresses, output_file_name, endpoint, report_type, retry, api_key, api_secret, files_path): """Creates an Excel file made up of combining the Value Report or Rental Report Excel output for the provided addresses. Args: addresses: A list of (address, zipcode) tuples output_file_name: A file nam...
limit is reached api_key: optional API Key api_secret: optional API Secret files_path: Path to save individual files. If None, don't save files """ # create the master workbook to output master_workbook = openpyxl.Workbook() if api_key is not None and api_secret is not None: client = ApiClient(api_key, api_secret) else...
xlsx content in a workbook. for index, addr in enumerate(addresses): print('Processing {}'.format(addr[0])) result = _get_excel_report( client, endpoint, addr[0], addr[1], report_type, retry) if not result['success']: print('Error retrieving report for {}'.format(addr[0])) print(result['content']) errors.append({'addre...
in master_workbook.get_sheet_names(): master_ws = master_workbook.get_sheet_by_name(sheet_name) else: master_ws = master_workbook.create_sheet(sheet_name) # get all the rows in the address worksheet orig_rows = orig_wb.get_sheet_by_name(sheet_name).rows if sheet_name == 'Summary' or sheet_name == 'Chart Data': _process...
errors_sheet = master_workbook.create_sheet('Errors') for error_idx, error in enumerate(errors): errors_sheet.cell(row=error_idx+1, column=1, value=error['address']) errors_sheet.cell(row=error_idx+1, column=2, value=error['message']) # save the master workbook to output_file_name adjust_column_width_workbook(master_wo...
def create_excel_workbook(data, result_info_key, identifier_keys): """Calls the analytics_data_excel module to create the Workbook""" workbook = analytics_data_excel.get_excel_workbook(data, result_info_key, identifier_keys) adjust_column_width_workbook(workbook) return workbook