def test_specify_client_config_in_code(): client = Client( configuration={ "base_url": "https://cad.onshape.com", "access_key": "USER_ACCESS_KEY", "secret_key": "USER_SECRET_KEY", }) assert client.configuration.api_key["SECRET_KEY"] == "USER_SECRET_KEY" assert client.configuration.api_key["ACCESS_KEY"] == "USER_ACCESS_KEY" # Reset client: client = Client() assert client.configuration.api_key["SECRET_KEY"] != "USER_SECRET_KEY" assert client.configuration.api_key["ACCESS_KEY"] != "USER_ACCESS_KEY"
def get_client(self): """Start the client if the client isn't already started.""" try: client = Client.get_client(create_if_needed=False) except Exception as e: if self.stack == "STAGE": base_url = "https://staging.dev.onshape.com" token_uri = "https://staging-oauth.dev.onshape.com/oauth/token" authorization_uri = "https://staging-oauth.dev.onshape.com/oauth/authorize" elif self.stack == "DEMOC": base_url = "https://demo-c.dev.onshape.com" token_uri = "https://demo-c-oauth.dev.onshape.com/oauth/token" authorization_uri = "https://demo-c-oauth.dev.onshape.com/oauth/authorize" # PROD stack is default. else: base_url = "https://cad.onshape.com" token_uri = "https://oauth.onshape.com/oauth/token" authorization_uri = "https://oauth.onshape.com/oauth/authorize" client = Client( configuration={ "client_id": self.client_id, "client_secret": self.client_secret, "base_url": base_url, "token_uri": token_uri, "authorization_uri": authorization_uri, "oauth_authorization_method": OAuthAuthorizationMethods.MANUAL_FLOW, "scope": ["OAuth2Read"], "redirect_uri": self.redirect_uri, "access_token": self.access_token, "refresh_token": self.refresh_token }) return client
def client() -> Client: """Client needed to make API calls.""" try: client = Client.get_client() except Exception as e: client = Client(stack_key="onshape_client_test") return client
def test_import_file(assets, new_document): """Import a file from the local file system. Returns the URL of the resulting element if translated.""" client = Client() cube_path = assets / 'Cube.x_t' file = open(cube_path, 'rb').read() r = client.blob_elements_api.upload_file_create_element( new_document.did, new_document.wvmid, _preload_content=False) # file=file, translate=True, encodedFilename=cube_path.name, media_type="application/stl", translation_id = get_field(r, 'translationId') print("The translationId is: {}.".format(translation_id)) state = 'ACTIVE' while state == 'ACTIVE': time.sleep(2) r = client.translation_api.get_translation(translation_id, _preload_content=False) state = get_field(r, "requestState") element_id = get_field(r, 'resultElementIds')[0] # Make the actual download when the translation is done, otherwise report the error if state == "DONE": print( "Translated document available at {host}/documents/{did}/w/{wid}/e/{eid}" .format(host=client.configuration.host, did=get_field(r, 'documentId'), wid=get_field(r, 'workspaceId'), eid=element_id)) else: print("An error ocurred on the server! Here is the response: \n") return element_id
def test_specify_client_config_in_code(): # Clear the current instance if there is one Client.__instance = None client = Client(configuration={ "base_url": "https://cad.onshape.com", "access_key": "USER_ACCESS_KEY", "secret_key": "USER_SECRET_KEY" }) assert client.configuration.api_key["SECRET_KEY"] == "USER_SECRET_KEY" assert client.configuration.api_key["ACCESS_KEY"] == "USER_ACCESS_KEY"
def connectToClient(verbose=False): # Setting up the client args["client"] = Client( configuration={ "base_url": args["base"], "access_key": args["key"], "secret_key": args["secret"] }) args["headers"] = { 'Accept': 'application/vnd.onshape.v1+json; charset=UTF-8;qs=0.1', 'Content-Type': 'application/json' } if (verbose): print("Connected to Onshape Client!", end="\n\n")
def __init__(self, url, *args, client=None, **kwargs): self.client = client if client else Client() self.original_url = url parsed_vals = urlparse(url) self.base_url = parsed_vals.scheme + "://" + parsed_vals.netloc path_list = parsed_vals.path.split('/') self.did = path_list[2] self.wvmid = path_list[4] self.wvm = path_list[3] if len(path_list) > 7: eid = path_list[8] optional_microversion = path_list[6] else: eid = path_list[6] # This is the microversion retrieved from get_microversion_path() and represents a part that is pointing towards # both a version/workspace and a microversion. optional_microversion = None self.eid = eid self.optional_microversion = optional_microversion
def initializeClient(self): """ Initializes all of the onshape info for API communication """ self.key = "" self.secret = "" with open("api-key", "r") as f: self.key = f.readline().rstrip() self.secret = f.readline().rstrip() self.base_url = 'https://cad.onshape.com' self.headers = { 'Accept': 'application/vnd.onshape.v1+json', 'Content-Type': 'application/json' } self.currentCourse = 'ME134' self.query_params = {} self.sharedQ = {'filter': 2, 'q': self.currentCourse} self.client = Client( configuration={ "base__url": self.base_url, "access_key": self.key, "secret_key": self.secret })
sys.setrecursionlimit(100000) # first point should be last point, add first point to end of string key = "" secret = "" with open("../scripts/api-key", "r") as f: key = f.readline().rstrip() secret = f.readline().rstrip() base_url = 'https://rogers.onshape.com' client = Client(configuration={ "base_url": base_url, "access_key": key, "secret_key": secret }) did = "aec16876714d70a447e5b140" wid = "c96b1b15861efbe1cf7dd9be" # eid = "db62cec33be087b52f777ec3" eid = "92e70961b3ada9cd69667064" get_string = "/api/featurestudios/d/aec16876714d70a447e5b140/w/c96b1b15861efbe1cf7dd9be/e/92e70961b3ada9cd69667064" update_string = "/api/featurestudios/d/aec16876714d70a447e5b140/w/c96b1b15861efbe1cf7dd9be/e/92e70961b3ada9cd69667064" post_api_call = base_url + update_string get_api_call = base_url + get_string image = Image.open('complex-high.jpg') f = image.load()
def client(): return Client()
from onshape_client.client import Client, OAuthAuthorizationMethods client = Client(stack_key="prod-oauth-full") def test_client(configurable_cube): call_api(configurable_cube, client) def test_manual_oauth_flow(configurable_cube): client.oauth_authorization_method = OAuthAuthorizationMethods.MANUAL_FLOW # save refresh token then put in later. refresh_token = client.refresh_token client.refresh_token = "" client.configuration.access_token = "" try: call_api(configurable_cube, client) except Exception as e: client.refresh_token = refresh_token call_api(configurable_cube, client) def call_api(cube, client): client.elements_api.get_configuration3(cube.did, cube.wvm, cube.wvmid, cube.eid)
def client(): try: client = Client.get_client() except Exception as e: client = Client(stack_key='onshape_client_test') return client
with open('config.yaml') as f: # for Onshape data = yaml.load(f, Loader=yaml.FullLoader) my_configuration = data["my_configuration"] # for Valispace url = data["url"] project_name = data["project_name"] username = data["username"] password = data["password"] # Get parts from Onshape project onshape_client = Client(configuration=my_configuration) # /api/parts/d/cf9ae4af8d5dd69e0be8390a/w/d6cf21a6b4d1850415a83496?withThumbnails=false&includeFlatParts=false&includePropertyDefaults=false data = onshape_client.parts_api did = "cf9ae4af8d5dd69e0be8390a" wvm = "w" wvmid = "d6cf21a6b4d1850415a83496" parts_data = data.get_parts_wmv(did=did, wvm=wvm, wvmid=wvmid) name_list = [] for element in parts_data: name_list.append(element["name"])
"""Export a STEP file """ from onshape_client.client import Client from onshape_client.onshape_url import OnshapeElement from onshape_client.models.bt_translate_format_params import BTTranslateFormatParams import time import json import os.path client = Client(stack_key="prod") # We're saving these files to the home directory ("~") client.configuration.temp_folder_path = os.path.expanduser("~") # Turn the URL into an "OnshapeElement" url = "https://cad.onshape.com/documents/cca81d10f239db0db9481e6f/v/aaa25d18038e06f0b2964e2d/e/69c9eedda86512966b20bc90" cube = OnshapeElement(url, client=client) # Create the params. Note there are far more params that can be specified. params = BTTranslateFormatParams(element_id=cube.eid, format_name="STEP", store_in_document=False) # Call the client response = client.part_studios_api.translate_format5( cube.did, cube.wvm, cube.wvmid, cube.eid, bt_translate_format_params=params)
def client(): try: client = Client.get_client() except Exception as e: client = Client() return client
from onshape_client.client import Client from onshape_client.onshape_url import OnshapeElement """There are three ways to authenticate the client. Passing variables directly during instantiation of the Client object, providing environment variables, or using a YAML file in the home directory entitled '.onshape_client_config.yaml'.""" client = Client() """First, we're going to inspect the feature list of the example configured cube used for onshape-client testing.""" my_cube_ps = OnshapeElement( 'https://cad.onshape.com/documents/cca81d10f239db0db9481e6f/w/80887f5994121967bf4d59a6/e/69c9eedda86512966b20bc90' ) features = client.part_studios_api.get_features1(my_cube_ps.did, my_cube_ps.wvm, my_cube_ps.wvmid, my_cube_ps.eid) """Print the order of the features""" print(",".join([f.name for f in features.features]))
def imageToOnshape(api_path, image_path, feature_title, ids=["", "", ""], scale=100, thresh=100): key = "" secret = "" with open(api_path, "r") as f: key = f.readline().rstrip() secret = f.readline().rstrip() did, wid, eid = ids base_url = 'https://rogers.onshape.com' client = Client(configuration={ "base_url": base_url, "access_key": key, "secret_key": secret }) get_string = "/api/featurestudios/d/" + did + "/w/" + wid + "/e/" + eid update_string = get_string post_api_call = base_url + update_string get_api_call = base_url + get_string # read the image img = cv2.imread(image_path) width = int(img.shape[1] * scale / 100) height = int(img.shape[0] * scale / 100) dim = (width, height) image = cv2.resize(img, dim, interpolation=cv2.INTER_NEAREST) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) _, binary = cv2.threshold(gray, thresh, thresh, cv2.THRESH_BINARY_INV) # GRAB EXTERNAL CONTOUR contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) data = np.vstack(contours).squeeze() # np.savetxt("test-test.txt", data, fmt="%d") x = [sub[0] / scale for sub in data] y = [sub[1] / scale for sub in data] formatter_x = [] formatter_y = [] for i, pixel in enumerate(x): formatter_x.append("%.6f" % (pixel)) formatter_y.append("%.6f" % (y[i])) formatter_y = formatter_y[:-1] formatter_x = formatter_x[:-1] formatter_x.append("%.6f" % (x[0])) formatter_y.append("%.6f" % (y[0])) test_string = "vector( 2.000000, 1.000000) * mm" overall_string = "" for i in range(len(formatter_x)): if i == len(formatter_x) - 1: overall_string += ("vector(%s, %s) * inch" % (formatter_x[i], formatter_y[i])) else: overall_string += ("vector(%s, %s) * inch, " % (formatter_x[i], formatter_y[i])) if i % 5 == 0: overall_string += "\n" start_string = """FeatureScript 1301; import(path : "onshape/std/geometry.fs", version : "1301.0"); annotation { "Feature Type Name" : "Python3 Feature" } export const myFeature = defineFeature(function(context is Context, id is Id, definition is map) precondition { // Define the parameters of the feature type } { var sketch1 = newSketch(context, id + "sketch1", { "sketchPlane" : qCreatedBy(makeId("Top"), EntityType.FACE) }); skPolyline(sketch1, "polyline1", { "points" : [""" start_string = start_string.replace("Python3 Feature", feature_title) end_string = """]}); skSolve(sketch1); // Define the function's action });""" full_fs = (start_string + overall_string + end_string) # Make API Calls headers = { 'Accept': 'application/vnd.onshape.v1+json', 'Content-Type': 'application/json' } r = client.api_client.request('GET', url=get_api_call, query_params={}, headers=headers) result = json.loads(r.data) #Find rejectMicroversionSkew, serializationVersion, sourceMicroversion serializationVersion = result["serializationVersion"] sourceMicroversion = result["sourceMicroversion"] rejectMicroversionSkew = result["rejectMicroversionSkew"] body = { "contents": full_fs, "serializationVersion": str(serializationVersion), "sourceMicroversion": str(sourceMicroversion), "rejectMicroversionSkew": str(rejectMicroversionSkew) } r = client.api_client.request("POST", url=post_api_call, query_params={}, headers=headers, body=body) result2 = json.loads(r.data)
) exit() if (not args.base): args.base = "https://rogers.onshape.com" print(". . . Defaulting to rogers.onshape.com . . .") # Gets api key and secret key with open("api-key", "r") as f: accessKey = f.readline().rstrip() secretKey = f.readline().rstrip() # Setting up the client client = Client(configuration={ "base_url": args.base, "access_key": accessKey, "secret_key": secretKey }) headers = { 'Accept': 'application/vnd.onshape.v1+json; charset=UTF-8;qs=0.1', 'Content-Type': 'application/json' } print(client) # print(client.__dict__) # creates path fixed_url = '/api/assemblies/d/did/w/wid/e/eid' fixed_url = fixed_url.replace('did', args.did) fixed_url = fixed_url.replace('wid', args.wid) fixed_url = fixed_url.replace('eid', args.eid)