Beispiel #1
0
def element(request, client, element_bank) -> OnshapeElement:
    """ Get a particular element from the bank by parametrizing the test with: `@pytest.mark.parametrize('assembly',
    ['three_axes'], indirect=True)`
    :param request:
    :param client:
    :return: OnshapeElement
    """
    element_key = request.param
    try:
        return OnshapeElement(element_bank[element_key])
    except KeyError as e:
        raise KeyError(f"Cannot find '{element_key}' in the element bank.")
    def import_item(self, import_item):
        did = self.onshape_element.did
        wid = self.onshape_element.wvmid
        path = write_to_file(import_item["file"])
        eid = import_file(path, did, wid)
        onshape_element = self.onshape_element
        onshape_element.eid = eid
        url = onshape_element.get_url()
        mass_properties = client.part_studios_api.get_mass_properties(did, 'w', wid, eid) # type: BTMassPropResponse
        volume = mass_properties.bodies["-all-"].volume[0]*1000000000
        bounding_box = client.part_studios_api.get_bounding_boxes2(did, 'w', wid, eid, _preload_content=False)
        bounding_box = json.loads(bounding_box.data)
        x_span = (bounding_box["highX"]-bounding_box["lowX"])*1000
        y_span = (bounding_box["highY"]-bounding_box["lowY"])*1000
        z_span = (bounding_box["highZ"]-bounding_box["lowZ"])*1000
        bounding_box = "L = {x_span}, W = {y_span}, H = {z_span}".format(x_span=x_span, y_span=y_span, z_span=z_span)

        if "part_metadata" in import_item or "element_metadata" in import_item:
            meta_data_to_be_set = MetaDataBody(OnshapeElement.create_from_ids(did, "w", wid, eid))
            if "part_metadata" in import_item:
                part_metadata = import_item["part_metadata"]
                # Add the volume part volume property from the API:
                meta_data_to_be_set.add_to_part_metadata("Part Volume", volume)
                meta_data_to_be_set.add_to_part_metadata("Bounding Box", bounding_box)
                for k, v in part_metadata.items():
                    # For the fixed field items, set for the first part
                    if k != "additionalItems":
                        meta_data_to_be_set.add_to_part_metadata(k,
                                                                 v)
                    else:
                        for custom_metadata_item in v:
                                meta_data_to_be_set.add_to_part_metadata(custom_metadata_item["part_id"],
                                                                     custom_metadata_item["property_name"],
                                                                     custom_metadata_item["new_value"])
            if "element_metadata" in import_item:
                element_metadata = import_item["element_metadata"]
                for k, v in element_metadata.items():
                    if k != "additionalItems":
                        meta_data_to_be_set.add_to_element_metadata(k,v)
                    else:
                        for custom_metadata_item in v:
                            meta_data_to_be_set.add_to_element_metadata(custom_metadata_item["property_name"],
                                                                        custom_metadata_item["new_value"], eid=eid)
            meta_data_to_be_set.send()

        if "bounding_box" in import_item and import_item["bounding_box"]:
            feature_path = "bound_all_set_metadata.json"
            # feature_path = "bound_all_feature.json"
            # feature_path = "make_cube_feature.json"
            with open(os.path.dirname(__file__) + "/assets/" + feature_path, "r") as f:
                body = {"feature": json.loads(f.read())}
            client.part_studios_api.add_feature1(did, "w", wid, eid, body=body)
def test_get_variables(client):
    element = OnshapeElement(
        "https://cad.onshape.com/documents/78aa66ffe6f1daceb9cfad3d/v/e36c0bd857c2a2a8b2107a40/e/92549789b92e9aa35f676f4e")
    script_call = BTFeatureScriptEvalCall(script=script_get_variables)
    response = client.part_studios_api.eval_feature_script(element.did,
                                                           element.wvm,
                                                           element.wvmid,
                                                           element.eid,
                                                           bt_feature_script_eval_call=script_call,
                                                           _preload_content=False)
    measurements = json.loads(response.data.decode("utf-8"))["result"]["message"]["value"]
    parsed_measurements = parse_variables_from_map(measurements)
    print("Measurements: \n" + str(parsed_measurements))
    assert parsed_measurements['block_height'] == "5.0*meter"
Beispiel #4
0
 def copy_workspace(copied_from):
     params = BTCopyDocumentParams(new_name=name_factory(), is_public=True)
     doc = client.documents_api.copy_workspace(
         copied_from.did,
         copied_from.default_workspace,
         bt_copy_document_params=params,
         _preload_content=False,
     )
     doc = json.loads(doc.data.decode("utf-8"))
     doc = OnshapeElement.create_from_ids(
         did=doc["newDocumentId"], wvm="w", wvmid=doc["newWorkspaceId"]
     )
     created_docs.append(doc)
     return doc
def test_assembly_definition_performance(client):
    n_calls = 10
    calls = []
    cube_asm = OnshapeElement(
        "https://cad.onshape.com/documents/ee5f3dea1b2b6196cba97e4a/v/6935ab731cfe24915c2b4ac8/e/2e54df6ea6c0657369a57131"
    )
    for i in range(n_calls):
        start_time = time.time()
        client.assemblies_api.get_assembly_definition(cube_asm.did,
                                                      cube_asm.wvm,
                                                      cube_asm.wvmid,
                                                      cube_asm.eid,
                                                      _preload_content=False)
        calls.append(time.time() - start_time)
    assert sum(calls) / len(calls) < 1
def test_get_centers(client):
    element = OnshapeElement(
        "https://cad.onshape.com/documents/3cdcb81d025b7faf96aaed73/v/43e49db3229b09381dc936f7/e/258deef46af76a558fad8f27")
    queries = [{"key" : "hole_centers", "value":["IJ"]}]
    script_call = BTFeatureScriptEvalCall(script=script_get_hole_center, queries=queries)
    response = client.part_studios_api.eval_feature_script(element.did,
                                                           element.wvm,
                                                           element.wvmid,
                                                           element.eid,
                                                           bt_feature_script_eval_call=script_call,
                                                           _preload_content=False)
    result = json.loads(response.data.decode("utf-8"))
    coords = result['result']['message']['value'][0]['message']['value']
    assert coords[0]['message']['value'] == 0.14818060398101807
    assert coords[1]['message']['value'] == 0.22330030798912048
    assert coords[2]['message']['value'] == 0.508
def test_get_all_fs(client):
    # 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/ea1c0fef91272adff0cc4b41/w/65efb40b6df7b9206b2a10b5/e/6921aecc8424c978fe8c78ce"
    cube = OnshapeElement(url, client=client)

    my_elements = client.documents_api.get_elements3(cube.did, cube.wvm,
                                                     cube.wvmid)
    for element in my_elements:
        if element.element_type == 'FEATURESTUDIO':
            fs_contents = client.feature_studios_api.get_feature_studio_contents1(
                cube.did, cube.wvm, cube.wvmid, element.id)
            file_path = Path(__file__).parent / 'tmp' / (
                "{name}::{id}.fs".format(name=element.name, id=element.id))
            file = file_path.open(mode='w')
            file.write(fs_contents.contents)
            file.close()
Beispiel #8
0
    def __init__(self, name=None, max_points=1,
                 onshape_element=None):
        """Initialize the definition of the check"""
        self.max_points = max_points
        # The points scored for this check
        self.points = 0
        self.name = name if name else self.__name__
        # Start client on the fly if need be.
        self.client = Client.get_client()

        # A key value map for template substitutions
        self.template_context = {"a_test_variable_name": "a test variable value"}

        self.onshape_element = onshape_element if isinstance(onshape_element, OnshapeElement) or not onshape_element \
            else OnshapeElement(onshape_element)

        self.did = self.onshape_element.did
        self.wvm = self.onshape_element.wvm
        self.wvmid = self.onshape_element.wvmid
        self.eid = self.onshape_element.eid

        # Whether or not the check passed
        self.passed = False
Beispiel #9
0
    BTMIndividualQueryBase139
)
import json
from onshape_client.oas.models.bt_feature_definition_call1406 import (
    BTFeatureDefinitionCall1406,
)
from onshape_client.onshape_url import OnshapeElement
from onshape_client.oas.models.bt_id_translation_params import BTIdTranslationParams
from onshape_client.oas.models.btm_feature134 import BTMFeature134
from onshape_client.oas.models.btm_parameter_enum145 import BTMParameterEnum145
from onshape_client.oas.models.btm_parameter_quantity147 import BTMParameterQuantity147
from onshape_client.client import Client 
from onshape_client.oas import BTCopyDocumentParams, BTDocumentSearchParams

element = OnshapeElement(
	'https://rogers.onshape.com/documents/b7c65d78bde731408815188e/w/09daa8ec5418b4d1e583d4b3/e/96d39b57bfcc8cca0d96c2b5'
)

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})

Square0 = BTMSketch151(entities=[BTMSketchCurveSegment155(start_point="LINE1.start", end_point_id="LINE1.end", start_param=0.0, end_param=1.0, geometry=BTCurveGeometryLine117(pnt_x=0.0, pnt_y=0.0, dir_x=0.0, dir_y=0.0254, bt_type="BTCurveGeometryLine-117"), entity_id="LINE1", bt_type="BTMSketchCurveSegment-155"),BTMSketchCurveSegment155(start_point="LINE2.start", end_point_id="LINE2.end", start_param=0.0, end_param=1.0, geometry=BTCurveGeometryLine117(pnt_x=0.0, pnt_y=0.0254, dir_x=0.0254, dir_y=0.0, bt_type="BTCurveGeometryLine-117"), entity_id="LINE2", bt_type="BTMSketchCurveSegment-155"),BTMSketchCurveSegment155(start_point="LINE3.start", end_point_id="LINE3.end", start_param=0.0, end_param=1.0, geometry=BTCurveGeometryLine117(pnt_x=0.0254, pnt_y=0.0254, dir_x=0.0, dir_y=-0.0254, bt_type="BTCurveGeometryLine-117"), entity_id="LINE3", bt_type="BTMSketchCurveSegment-155"),BTMSketchCurveSegment155(start_point="LINE4.start", end_point_id="LINE4.end", start_param=0.0, end_param=1.0, geometry=BTCurveGeometryLine117(pnt_x=0.0254, pnt_y=0.0, dir_x=-0.0254, dir_y=0.0, bt_type="BTCurveGeometryLine-117"), entity_id="LINE4", bt_type="BTMSketchCurveSegment-155"),], name="Square", parameters=[BTMParameterQueryList148(parameter_id="sketchPlane", queries=[BTMIndividualQuery138(deterministic_ids=['JDC'])]),BTMParameterQuantity147(expression="1*in", parameter_id="length", bt_type="BTMParameterQuantity-147"),], constraints=[BTMSketchConstraint2(constraint_type="COINCIDENT",parameters=[BTMParameterString149(value="point1", parameter_id="localFirst", bt_type="BTMParameterString-149"),BTMParameterString149(value="'LINE1.start", parameter_id="localSecond", bt_type="BTMParameterString-149"),],entity_id="constrainId",bt_type="BTMSketchConstraint-2"),BTMSketchConstraint2(constraint_type="LENGTH",parameters=[BTMParameterString149(value="point1", parameter_id="localFirst", bt_type="BTMParameterString-149"),BTMParameterString149(value="'LINE1.start", parameter_id="localSecond", bt_type="BTMParameterString-149"),BTMParameterQuantity147(expression="1*in", parameter_id="length", bt_type="BTMParameterQuantity-147"),],entity_id="constrainId",bt_type="BTMSketchConstraint-2"),], bt_type="BTMSketch-151")
Beispiel #10
0
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)

translation_id = response.id
Beispiel #11
0
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
})

element = OnshapeElement(
    "https://rogers.onshape.com/documents/b7c65d78bde731408815188e/w/09daa8ec5418b4d1e583d4b3/e/fbca3f5c681a7618c9d7d895"
)

sweep_cube = 'https://rogers.onshape.com/documents/aec16876714d70a447e5b140/w/c96b1b15861efbe1cf7dd9be/e/5f5788dd8bef0635f2776ac5'
normal = 'b7c65d78bde731408815188e/w/09daa8ec5418b4d1e583d4b3/e/fbca3f5c681a7618c9d7d895'

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/vnd.onshape.v1+json'
}
r = client.api_client.request(
    method='GET',
    url=base_url +
    '/api/partstudios/d/aec16876714d70a447e5b140/w/c96b1b15861efbe1cf7dd9be/e/5f5788dd8bef0635f2776ac5/features',
    query_params={},
    headers=headers)
Beispiel #12
0
def get_parsed_measurements(link):
    """Parses the output of the Onshape Documenter feature found in the Onshape
    document at the given url.

    Args:
        link: URL of Onshape document

    Returns:
        measurements: dictionary of parsed variables
        templates: list of templates to move from doc_files and render in the
            design specs.

    >>> link = 'https://cad.onshape.com/documents/c3a8ce032e33ebe875b9aab4/v/2990aab7c08553622d0c1402/e/e09d11406e7a9143537efe3a'
    >>> measurements, templates = get_parsed_measurements(link)
    >>> templates
    ['./Entrance_Tank/LFOM.rst', './Entrance_Tank/Tank_Design_Algorithm.rst']
    >>> measurements['W.Et']
    '64.1 cm'
    >>> measurements['N.LfomOrifices']
    [13.0, 3.0, 4.0, 4.0]
    >>> measurements['HL.Lfom']
    '20.0 cm'
    >>> measurements['H.LfomOrifices']
    ['2.22 cm', '7.41 cm', '12.59 cm', '17.78 cm']
    >>> measurements['D.LfomOrifices']
    '4.45 cm'
    >>> measurements['B.LfomRows']
    '5.0 cm'
    """
    script = r"""
        function (context is Context, queries is map)
        {
            return getAttributes(context, {
                "entities" : qEverything(),
            });
        }
        """

    client = Client(
        configuration = {
            "base_url": "https://cad.onshape.com",
            "access_key": "ekAHCj04TtODlvlI9yWj2bjB",
            "secret_key": "sS11vEOD5CavkLVcZshLBgfBlB5aBvnpz6v3oEvC0bN0zxhW"
        }
    )

    element = OnshapeElement(link)

    script_call = BTFeatureScriptEvalCall2377(script=script)
    response = client.part_studios_api.eval_feature_script(
        element.did,
        element.wvm,
        element.wvmid,
        element.eid,
        bt_feature_script_eval_call_2377=script_call,
        _preload_content=False,
    )

    attributes = json.loads(response.data.decode("utf-8"))["result"][msg_str][val_str]
    fields = ["variables", "template", "index", "process"]

    measurements, templates = parse_attributes(attributes, fields)

    return measurements, templates
Beispiel #13
0
'''
Export an STL
==============

Demos 307 redirects with the Onshape API
'''

from onshape_client.client import Client
from onshape_client.onshape_url import OnshapeElement, ConfiguredOnshapeElement
from onshape_client.units import u

client = Client()

# Turn the URL into an "OnshapeElement"
url = "https://cad.onshape.com/documents/cca81d10f239db0db9481e6f/v/aaa25d18038e06f0b2964e2d/e/69c9eedda86512966b20bc90"
cube = OnshapeElement(url, client=client)

# get the STL export
stl = client.part_studios_api.export_stl1(cube.did, cube.wvm, cube.wvmid, cube.eid, _preload_content=False)

print("Resulting STL data (unconfigured): \n" + stl.data)

cube = ConfiguredOnshapeElement(url, client=client)
cube.update_current_configuration({'size': 40 * u.inch, 'edge_configuration': 'chamfered'})

# get the STL export
stl = client.part_studios_api.export_stl1(cube.did, cube.wvm, cube.wvmid, cube.eid, configuration=cube.get_configuration_string(), _preload_content=False)

print("Resulting STL data (configured): \n" + stl.data)
Beispiel #14
0
def test_sub_sub_sub_assembly_instance_insert(client, element):
    """Ensures inner assemblies are inserted as expected by inserting sub-assembly at +1 m in X, then inserting that
    assembly at +1 in X, and sees if we ended up back at the origin."""
    def make_version(name, did):
        return json.loads(Client.get_client().documents_api.create_version(
            did,
            bt_version_or_workspace_params=BTVersionOrWorkspaceParams(
                name=name + "-" + str(datetime.now()), document_id=did),
            _preload_content=False,
        ).data)["id"]

    origin = OnshapeElement(
        "https://cad.onshape.com/documents/ba13458e7ebfd1755645d5d1/w/031ba2bcb4b13b77bc5c43f7/e/af7fd0b2eac7ad63477370be"
    )
    assembly_pushed_x = OnshapeElement(
        "https://cad.onshape.com/documents/ba13458e7ebfd1755645d5d1/w/031ba2bcb4b13b77bc5c43f7/e/b340f69741da2eaba07ddc1f"
    )
    assembly_pulled_x = OnshapeElement(
        "https://cad.onshape.com/documents/ba13458e7ebfd1755645d5d1/w/031ba2bcb4b13b77bc5c43f7/e/6c9bb5a752c0b5b66610b918"
    )

    origin_transform = [
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
    ]

    push_x_transform = [
        1.0,
        0.0,
        0.0,
        1.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
    ]

    pull_x_transform = [
        1.0,
        0.0,
        0.0,
        -1.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
    ]

    three_axes_instance = BTAssemblyInstanceDefinitionParams(
        document_id=element.did,
        version_id=element.wvmid,
        element_id=element.eid,
        is_assembly=True,
    )

    client.assemblies_api.insert_transformed_instances(
        origin.did,
        origin.eid,
        origin.wvmid,
        BTAssemblyTransformedInstancesDefinitionParams(transform_groups=[
            TransformGroup(transform=origin_transform,
                           instances=[three_axes_instance])
        ]),
    )

    origin_version = make_version("orogin", origin.did)

    origin_instance = BTAssemblyInstanceDefinitionParams(
        document_id=origin.did,
        version_id=origin_version,
        element_id=origin.eid,
        is_assembly=True,
    )

    client.assemblies_api.insert_transformed_instances(
        assembly_pushed_x.did,
        assembly_pushed_x.eid,
        assembly_pushed_x.wvmid,
        BTAssemblyTransformedInstancesDefinitionParams(transform_groups=[
            TransformGroup(transform=push_x_transform,
                           instances=[origin_instance])
        ]),
    )

    pushed_x_version = make_version("pushed_x", origin.did)

    assembly_pushed_x_instance = BTAssemblyInstanceDefinitionParams(
        document_id=assembly_pushed_x.did,
        version_id=pushed_x_version,
        element_id=assembly_pushed_x.eid,
        is_assembly=True,
    )

    client.assemblies_api.insert_transformed_instances(
        assembly_pulled_x.did,
        assembly_pulled_x.eid,
        assembly_pulled_x.wvmid,
        BTAssemblyTransformedInstancesDefinitionParams(transform_groups=[
            TransformGroup(transform=pull_x_transform,
                           instances=[assembly_pushed_x_instance])
        ]),
    )

    result = client.assemblies_api.get_assembly_definition(
        assembly_pulled_x.did,
        assembly_pulled_x.wvm,
        assembly_pulled_x.wvmid,
        assembly_pulled_x.eid,
        _preload_content=False,
    )
    result = json.loads(result.data.decode("UTF-8"))
    final_transform = [
        t["transform"] for t in result["rootAssembly"]["occurrences"]
        if len(t["path"]) == 4
    ][0]
    assert final_transform == origin_transform
def configured_cube_version():
    return OnshapeElement(
        "https://cad.onshape.com/documents/cca81d10f239db0db9481e6f/v/ca51b7554314d6aab254d2e6/e/69c9eedda86512966b20bc90"
    )
def configured_cube_version_9_assembly():
    return OnshapeElement(
        "https://cad.onshape.com/documents/cca81d10f239db0db9481e6f/v/5bba9aca3622369df9dbe90c/e/32fbe5d87f9b2777a37ddee9"
    )
def test_creation_from_urls():
    assert OnshapeElement(
        "https://cad.onshape.com/documents/c8f8013d34183b1de74fa930/w/574b77701d8b74987c273500/e/455ef770951fe37de0b8ff08?configuration=List_TOpkWtvolR0KY4%3Dewf"
    ).configuration == "List_TOpkWtvolR0KY4=ewf"
Beispiel #18
0
# element.delete(                    element.make_version(              element.wvm                       
# element.did                        element.mass_properties            element.wvmid                     
# element.DRAWING_DATA_TYPE          element.microversion       

with open("../scripts/api-key", "r") as f: 
    key = f.readline().rstrip()
    secret = f.readline().rstrip()

base_url = 'https://rogers.onshape.com'

headers = {'Accept': 'application/vnd.onshape.v1+json', 'Content-Type': 'application/json'}

client = Client(configuration={"base_url": base_url, "access_key": key, "secret_key": secret})

element = OnshapeElement(
        "https://rogers.onshape.com/documents/b7c65d78bde731408815188e/w/09daa8ec5418b4d1e583d4b3/e/d3ef40a634c6d4d599dd78e3"
    )

# doc = client.documents_api.create_document(
#         bt_document_params=BTCopyDocumentParams(
#             owner_type_index=1, new_name="Test Python Client", owner_id=""
#         )
#     )
# print(doc)
def test_insert_point_sketch(client, part_studio):
    PLANE_ID = "JDC"  # The plane deterministic ID for the sketch
    plane_query = BTMParameterQueryList148(
        parameter_id="sketchPlane",
        queries=[BTMIndividualQuery138(deterministic_ids=[PLANE_ID])],
    )
    point = BTMSketchPoint158(
def drawing():
    return OnshapeElement(
        "https://cad.onshape.com/documents/cca81d10f239db0db9481e6f/v/9e1317a768623dc4520c27e4/e/7fce3984957af2cfda8d56cb"
    )
    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


if __name__ == "__main__":
    element = OnshapeElement(
        "http://localhost.dev.onshape.com:8080/documents/ee93985ceb928f7a7c79fed3/w/593971edd8336a08489ec7c0/e/c066cfbaf68e866b53cdb73f"
    )
    import_file(
        os.path.dirname(__file__) + "/assets/Cube.x_t", element.did,
        element.wvmid)
Beispiel #21
0
def new_document(request, client, name_factory):
    """Returns a blank new document."""
    doc = OnshapeElement.create(name_factory())
    yield doc
    doc.delete()
Beispiel #22
0
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
})
element = OnshapeElement(
    'https://rogers.onshape.com/documents/b7c65d78bde731408815188e/w/09daa8ec5418b4d1e583d4b3/e/cf9e349d44e4ac66367f48fe'
)

print('Sending Square0 to Onshape...')
funcTester(Square0, element, client)
sleep(.75)

print('Sending Square_Extrude1 to Onshape...')
funcTester(Square_Extrude1, element, client)
sleep(.75)

print('Sending Circle_On_a_Face2 to Onshape...')
funcTester(Circle_On_a_Face2, element, client)
sleep(.75)

print('Sending Extrude_Remove_Circle3 to Onshape...')
Beispiel #23
0
    with open(args.api_path, "r") as f:
        key = f.readline().rstrip()
        secret = f.readline().rstrip()
except Exception:
    print("-p flag not specified for api key path")
    exit()

base_url = 'https://rogers.onshape.com'

client = Client(configuration={
    "base_url": base_url,
    "access_key": key,
    "secret_key": secret
})

element = OnshapeElement(args.url)

# split the url to did, wid, eid
temp_url = args.url.split('/')
did = temp_url[4]
wid = temp_url[6]
eid = temp_url[8]

api_string = '/api/partstudios/d/did/w/wid/e/eid/features'
api_call = api_string.replace('did', did).replace('wid',
                                                  wid).replace('eid', eid)

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/vnd.onshape.v1+json'
}
"""For uploading a file and creating the element in one go.
"""

from onshape_client.client import Client
from onshape_client.onshape_url import OnshapeElement
from onshape_client.models.bt_feature_script_eval_call import BTFeatureScriptEvalCall
from onshape_client.utility import parse_quantity
import json

onshape_element = OnshapeElement(
    "https://cad.onshape.com/documents/cca81d10f239db0db9481e6f/w/80887f5994121967bf4d59a6/e/32fbe5d87f9b2777a37ddee9"
)
client = Client()
client.blob_elements_api.upload_file_create_element(onshape_element.did,
                                                    onshape_element.wvmid)
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 configured_cube_versioin_4_assembly():
    return OnshapeElement(
        "https://cad.onshape.com/documents/cca81d10f239db0db9481e6f/v/369ac699891d9659ce2d42ba/e/32fbe5d87f9b2777a37ddee9"
    )