def cancel_cmd_action(cmd_str, cmd_vars, cmd_dict): if ci.get_yes_no(prompt='Are you sure you want to cancel?', default='no') == 'yes': print('\nCommand cancelled...') return ci.CommandResponse(ci.COMMAND_ACTION_CANCEL, None) else: return ci.CommandResponse(ci.COMMAND_ACTION_NOP, None)
def create_html_action(row, action_dict): endpoints = action_dict['endpoints'] created = action_dict['created'] export_dir = Path.home().joinpath('export') dir_validator = ci.SimpleValidator(os.path.isdir) try: export_dir = ci.get_string(prompt='directory for html export: ', validators=dir_validator, default=str(export_dir)) except (ci.ValidationError): if ci.get_yes_no(prompt='Should I create the directory', default='no') == 'yes': os.mkdir(export_dir) else: print('Unable to export html') return toc_filename = Path(export_dir, TOC_FILENAME) with open(toc_filename, mode='w', encoding='utf-8') as f: create_toc(f, endpoints, created) for group in endpoints: for endpt in group['endpoints']: filename = Path(export_dir, endpt["name"] + '.html') with open(filename, mode='w', encoding='utf-8') as f: export_individual_endpoint_as_html(f, endpt) print('\n\n')
def list_documents_action(row, action_dict): # Uses Documents API/Get Documents # parms - q - search for string in name of document # filter - 0-9 for filter, 0 - my docs, 6- by owner, 7 by company, 9 by team # owner - owner id for filter 6 or 7, team if 9 # offset - offset into the page (max 20) # limit - number of documents returned per page c = action_dict['client'] doc_query = {'offset': 0, 'limit': 20} name_filter = ci.get_string( prompt='String to filter document names (hit enter for no filter)', required=False, commands=std_commands) if name_filter is not None and len(name_filter) > 0: doc_query['q'] = name_filter if ci.get_yes_no(prompt='Show only your documents', default='no', commands=std_commands) == 'yes': filter_val, owner = (0, None) # filter by company doc_query = {'filter': 0} elif ci.get_yes_no(prompt='Show documents for your company', default='no', commands=std_commands) == 'yes': doc_query = { 'filter': 7, 'owner': action_dict['company'] } # filter by company # elif ...: # TODO - implement other filters - team, owner, etc. #filter_val, owner = (9, action_dict['team']) # filter by team #doc_query = {'filter': 9, 'owner': action_dict['team']} # filter by team else: if ci.get_yes_no( prompt= "Are you sure you want to fetch with no filters... this could take a long time!", default='no') == 'no': print('Cancelling action') raise ci.COMMAND_ACTION_CANCEL docs = c.list_documents(query=doc_query) tbl = create_docs_table(c, docs) tbl.get_table_choice(required=False, commands=table_commands) print('\n')
def test_get_yes_no(self): input_str = u""" foo Yes """ with redirect_stdin(StringIO(input_str)): result = get_yes_no() print(result) assert (result == 'yes')
def rewrite_parts_and_show_post_table(c, did, wvm, eid, fields, filtered_parts): if ci.get_yes_no( prompt= 'Do you want to re-write the part numbers with the part names', default='no') == 'yes': rewrite_part_numbers(c, did, filtered_parts) # rewrite_top_level_part_numbers(c, did, top_level_parts) # show results print('\nParts after setting part numbers:') filtered_part_set = {part['name'] for part in filtered_parts} bom = c.get_assembly_bom(did, wvm, eid) bom_json = json.loads(bom.text) changed_parts = [ part for part in bom_json['bomTable']['items'] if part['name'] in filtered_part_set ] # for part in top_level_parts: # changed_parts.append(part) for part in changed_parts: part['partId'] = part['itemSource']['partId'] part['elementId'] = part['itemSource']['elementId'] style = ci.TableStyle(show_border=True, hrules=ci.RULE_NONE, rows_per_page=None) tbl = ci.create_table(changed_parts, fields=fields, field_names=fields, gen_tags=None, item_data=None, add_item_to_item_data=True, title=None, prompt=None, default_choice=None, default_str=None, default_action='table_item', style=style) tbl.show_table() sys.exit(0) else: print('Exiting without re-writing part numbers\n') sys.exit(0)
def get_bom_action(row, action_dict): print('\n') c = action_dict['client'] did = action_dict['did'] wvm = action_dict['wvm'] eid = action_dict['eid'] types = ["flattened", "top-level", "multi-level"] type_vals = { "flattened": (False, False), "top-level": (True, False), "multi-level": (True, True) } prompt_str = f'BOM type ({", ".join(types)})' type_cleaner = ci.ChoiceCleaner(types) use_type = ci.get_string(prompt=prompt_str, cleaners=type_cleaner, default="flattened", commands=std_commands) indented, multi_level = type_vals[use_type] print( f'Fetching {multi_level} BOM from OnShape (did={did}, wvm={wvm}, eid={eid})' ) response = c.get_assembly_bom(did, wvm, eid, indented=indented, multi_level=multi_level, generate_if_absent=True) response_json = json.loads(response.text) try: status = response_json['status'] if status == 404: msg = response_json['message'] print("\nStatus 404 returned: {}\n".format(msg)) return except: pass bom_table = response_json['bomTable'] format_ver = bom_table['formatVersion'] name = bom_table['name'] bom_type = bom_table['type'] created_at = bom_table['createdAt'] doc_name = bom_table['bomSource']['document']['name'] top_pn = bom_table['bomSource']['element']['partNumber'] try: top_revision = bom_table['bomSource']['element'][ 'revision'] # column may not be there.. except (KeyError): top_revision = '--' state = bom_table['bomSource']['element']['state'] title = ( f"\n\n{bom_type} {name} (format version {format_ver}) - {doc_name} ({state} {top_pn}{top_revision}) created_at: {created_at}" ) rows = [] for idx, item in enumerate(bom_table['items']): item_num = item['item'] qty = item['quantity'] part_num = item['partNumber'] desc = item['description'] revision = item['revision'] state = item['state'] rows.append( ci.TableItem([qty, part_num, revision, state, desc], tag=item_num)) col_names = "Qty PartNum Rev State Desc".split() ci.Table(rows, col_names=col_names, title=title, tag_str='ItemNums').show_table() print('\n') # export to csv if ci.get_yes_no(prompt='Export to CSV file', default='no') == 'yes': cmds = {'/cancel': ci.GetInputCommand(cancel_cmd_action)} file_name = ci.get_string(prompt="CSV file_name to export to: ", default=f"{top_pn}_bom_export.csv", commands=cmds) with open(file_name, "w", encoding='utf-8', newline='') as f: hdr = 'ITEM_NUM QUANTITY PART_NUM REVISION STATE DESCRIPTION' csv_writer = csv.writer(f) csv_writer.writerow([f'{bom_type} BOM for:', top_pn]) csv_writer.writerow([]) csv_writer.writerow(hdr.split()) for item in bom_table['items']: csv_writer.writerow([ item['item'], item['quantity'], item['partNumber'], item['revision'], item['state'], item['description'] ])
def reset_db_action(row, action_item): cmds = action_dict['commands'] if ci.get_yes_no(prompt='Delete all events? ', default='no', commands=cmds) == 'yes': action_dict['events'] = []
with open(toc_filename, mode='w', encoding='utf-8') as f: create_toc(f, endpoints, created) for group in endpoints: for endpt in group['endpoints']: filename = Path(export_dir, endpt["name"] + '.html') with open(filename, mode='w', encoding='utf-8') as f: export_individual_endpoint_as_html(f, endpt) print('\n\n') if __name__ == '__main__': if ci.get_yes_no( prompt= 'Fetch API endpoint information from Onshape (vs. use cached version)', default='no') == 'yes': stacks = {'cad': 'https://cad.onshape.com'} c = ClientExtended(stack=stacks['cad'], logging=False) print('Getting api endpoints from Onshape...\n') response = c.get_endpoints() endpoints = convert_response(response) created = datetime.datetime.now() if ci.get_yes_no(prompt='Save API endpoint information to file', default=FETCH_BY_DEFAULT) == 'yes': cache_content = (created.timestamp(), endpoints) with open(CACHED_ENDPOINT_FILE, 'w') as f: f.write(json.dumps(cache_content)) else: