# Azure Azure Digital Twins Core client library for Python
This package contains an SDK for Azure Digital Twins API to provide access to the Azure Digital Twins service for managing twins, models, relationships, etc.
## _Disclaimer_
_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_
## Getting started
### Introduction
Azure Digital Twins is a developer platform for next-generation IoT solutions that lets you create, run, and manage digital representations of your business environment, securely and efficiently in the cloud. With Azure Digital Twins, creating live operational state representations is quick and cost-effective, and digital representations stay current with real-time data from IoT and other data sources. If you are new to Azure Digital Twins and would like to learn more about the platform, please make sure you check out the Azure Digital Twins [official documentation page](https://docs.microsoft.com/azure/digital-twins/overview).
For an introduction on how to program against the Azure Digital Twins service, visit the [coding tutorial page](https://docs.microsoft.com/azure/digital-twins/tutorial-code) for an easy step-by-step guide. Visit [this tutorial](https://docs.microsoft.com/azure/digital-twins/tutorial-command-line-app) to learn how to interact with an Azure Digital Twin instance using a command-line client application. Finally, for a quick guide on how to build an end-to-end Azure Digital Twins solution that is driven by live data from your environment, make sure you check out [this helpful guide](https://docs.microsoft.com/azure/digital-twins/tutorial-end-to-end).
The guides mentioned above can help you get started with key elements of Azure Digital Twins, such as creating Azure Digital Twins instances, models, twin graphs, etc. Use this samples guide below to familiarize yourself with the various APIs that help you program against Azure Digital Twins.
### How to Install
Install [azure-digitaltwins-core][pypi_package_keys] and
[azure-identity][azure_identity_pypi] with [pip][pip]:
```Bash
pip install azure-digitaltwins-core azure-identity
```
[azure-identity][azure_identity] is used for Azure Active Directory
authentication as demonstrated below.
### How to use
#### Authentication, permission
To create a new digital twins client, you need the endpoint to an Azure Digital Twin instance and credentials.
For the samples below, the `AZURE_URL`, `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` environment variables have to be set.
The client requires an instance of [TokenCredential](https://docs.microsoft.com/dotnet/api/azure.core.tokencredential?view=azure-dotnet) or [ServiceClientCredentials](https://docs.microsoft.com/dotnet/api/microsoft.rest.serviceclientcredentials?view=azure-dotnet).
In this samples, we illustrate how to use one derived class: [DefaultAzureCredentials](https://docs.microsoft.com/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet).
> Note: In order to access the data plane for the Digital Twins service, the entity must be given permissions.
> To do this, use the Azure CLI command: `az dt rbac assign-role --assignee '<user-email | application-id>' --role owner -n '<your-digital-twins-instance>'`
DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
It attempts to use multiple credential types in an order until it finds a working credential.
##### Sample code
```python Snippet:dt_create_digitaltwins_service_client.py
# DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
# It attempts to use multiple credential types in an order until it finds a working credential.
# - AZURE_URL: The URL to the ADT in Azure
url = os.getenv("AZURE_URL")
# DefaultAzureCredential expects the following three environment variables:
# - AZURE_TENANT_ID: The tenant ID in Azure Active Directory
# - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant
# - AZURE_CLIENT_SECRET: The client secret for the registered application
credential = DefaultAzureCredential()
service_client = DigitalTwinsClient(url, credential)
```
## Key concepts
Azure Digital Twins is an Azure IoT service that creates comprehensive models of the physical environment. It can create spatial intelligence graphs to model the relationships and interactions between people, spaces, and devices.
You can learn more about Azure Digital Twins by visiting [Azure Digital Twins Documentation](https://docs.microsoft.com/azure/digital-twins/).
## Examples
You can explore the digital twins APIs (using the client library) using the samples project.
The samples project demonstrates the following:
- Instantiate the client
- Create, get, and decommission models
- Create, query, and delete a digital twin
- Get and update components for a digital twin
- Create, get, and delete relationships between digital twins
- Create, get, and delete event routes for digital twin
- Publish telemetry messages to a digital twin and digital twin component
### Create, list, decommission, and delete models
#### Create models
Let's create models using the code below. You need to pass an array containing list of models.
```Python Snippet:dt_models_lifecycle
temporary_component = {
"@id": component_id,
"@type": "Interface",
"@context": "dtmi:dtdl:context;2",
"displayName": "Component1",
"contents": [
{
"@type": "Property",
"name": "ComponentProp1",
"schema": "string"
},
{
"@type": "Telemetry",
"name": "ComponentTelemetry1",
"schema": "integer"
}
]
}
temporary_model = {
"@id": model_id,
"@type": "Interface",
"@context": "dtmi:dtdl:context;2",
"displayName": "TempModel",
"contents": [
{
"@type": "Property",
"name": "Prop1",
"schema": "string"
},
{
"@type": "Component",
"name": "Component1",
"schema": component_id
},
{
"@type": "Telemetry",
"name": "Telemetry1",
"schema": "integer"
}
]
}
new_models = [temporary_component, temporary_model]
models = service_client.create_models(new_models)
print('Created Models:')
print(models)
```
### List models
Using `list_models` to retrieve all created models
```Python Snippet:dt_models_lifecycle
listed_models = service_client.list_models()
for model in listed_models:
print(model)
```
### Get model
Use `get_model` with model's unique identifier to get a specific model.
```Python Snippet:dt_models_lifecycle
# Get a model
get_model = service_client.get_model(model_id)
print('Get Model:')
print(get_model)
```
### Decommission model
To decommision a model, pass in a model Id for the model you want to decommision.
```Python Snippet:dt_models_lifecycle
# Decommission a model
service_client.decommission_model(model_id)
```
### Delete model
To delete a model, pass in a model Id for the model you want to delete.
```Python Snippet:dt_models_lifecycle
# Delete a model
service_client.delete_model(model_id)
```
## Create and delete digital twins
### Create digital twins
For Creating Twin you will need to provide Id of a digital Twin such as `my_twin` and the application/json digital twin based on the model created earlier. You can look at sample application/json [here](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/digitaltwins/azure-digitaltwins-core/samples/dtdl/digital_twins).
```Python Snippet:dt_digitaltwins_lifecycle
digital_twin_id = 'digitalTwin-' + str(uuid.uuid4())
temporary_twin = {
"$metadata": {
"$model": model_id
},
"$dtId": digital_twin_id,
"Prop1": 42
}
created_twin = service_client.upsert_digital_twin(digital_twin_id, temporary_twin)
print('Created Digital Twin:')
print(created_twin)
```
### Get a digital twin
Getting a digital twin is extremely easy.
```Python Snippet:dt_digitaltwins_lifecycle
get_twin = service_client.get_digital_twin(digital_twin_id)
print('Get Digital Twin:')
print(get_twin)
```
### Query digital twins
Query the Azure Digital Twins instance for digital twins using the [Azure Digital Twins Query Store lanaguage](https://docs.microsoft.com/azure/digital-twins/concepts-query-language). Query calls support paging. Here's an example of how to query for digital twins and how to iterate over the results.
Note that there may be a delay between before changes in your instance are reflected in queries.
For more details on query limitations, see (https://docs.microsoft.com/azure/digital-twins/how-to-query-graph#query-limitations)
```Python Snippet:dt_digitaltwins_query
query_expression = 'SELECT * FROM digitaltwins'
query_result = service_client.query_twins(query_expression)
print('DigitalTwins:')
for twin in query_result:
print(twin)
```
### Delete digital twins
Delete a digital twin simply by providing Id of a digital twin as below.
```Python Snippet:dt_digitaltwins_lifecycle
service_client.delete_digital_twin(digital_twin_id)
```
## Get and update digital twin components
### Update digital twin components
To update a component or in other words to replace, remove and/or add a component property or subproperty within Digital Twin, you would need Id of a digital twin, component name and application/json-patch+json operations to be performed on the specified digital twin's component. Here is the sample code on how to do it.
```Python Snippet:dt_component_lifecycle
component_name = "Component1"
patch = [
{
"op": "replace",
"path": "/ComponentProp1",
"value": "value2"
}
]
service_client.update_component(digital_twin_id, component_name, patch)
```
### Get digital twin components
Get a component by providing name of a component and Id of digital twin to which it belongs.
```Python Snippet:dt_component_lifecycle
get_component = service_client.get_component(digital_twin_id, component_name)
print('Get Component:')
print(get_component)
```
## Create and list digital twin relationships
### Create digital twin relationships
`upsert_relationship` creates a relationship on a digital twin provided with Id of a digital twin, name of relationship such as "contains", Id of an relationship such as "FloorContainsRoom" and an application/json relationship to be created. Must contain property with key "\$targetId" to specify the target of the relationship. Sample payloads for relationships can be found [here](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/digitaltwins/azure-digitaltwins-core/samples/dtdl/relationships/hospitalRelationships.json).
```Python Snippet:dt_scenario
hospital_relationships = [
{
"$relationshipId": "BuildingHasFloor",
"$sourceId": building_twin_id,
"$relationshipName": "has",
"$targetId": floor_twin_id,
"isAccessRestricted": False
},
{
"$relationshipId": "BuildingIsEquippedWithHVAC",
"$sourceId": building_twin_id,
"$relationshipName": "isEquippedWith",
"$targetId": hvac_twin_id
},
{
"$relationshipId": "HVACCoolsFloor",
"$sourceId": hvac_twin_id,
"$relationshipName": "controlsTemperature",
"$targetId": floor_twin_id
},
{
"$relationshipId": "FloorContainsRoom",
"$sourceId": floor_twin_id,
"$relationshipName": "contains",
"$targetId": room_twin_id
}
]
for relationship in hospital_relationships:
service_client.upsert_relationship(
relationship["$sourceId"],
relationship["$relationshipId"],
relationship
)
```
### List digital twin relationships
`list_relationships` and `list_incoming_relationships` lists all the relationships and all incoming relationships respectively of a digital twin.
```Python Snippet:dt_relationships_list
relationships = service_client.list_relationships(digital_twint_id)
for relationship in relationships:
print(relationship)
```
```Python Snippet:dt_incoming_relationships_list
incoming_relationships = service_client.list_incoming_relationships(digital_twin_id)
for incoming_relationship in incoming_relationships:
print(incoming_relationship)
```
## Create, list, and delete event routes of digital twins
### Create event routes
To create an event route, provide an Id of an event route such as "myEventRouteId" and event route data containing the endpoint and optional filter like the example shown below.
```Python Snippet:dt_scenario
event_route_id = 'eventRoute-' + str(uuid.uuid4())
event_filter = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'"
route = DigitalTwinsEventRoute(
endpoint_name=event_hub_endpoint_name,
filter=event_filter
)
service_client.upsert_event_route(event_route_id, route)
```
For more information on the event route filter language, see the "how to manage routes" [filter events documentation](https://github.com/Azure/azure-digital-twins/blob/private-preview/Documentation/how-to-manage-routes.md#filter-events).
### List event routes
List a specific event route given event route Id or all event routes setting options with `list_event_routes`.
```Python Snippet:dt_event_routes_list
event_routes = service_client.list_event_routes()
for event_route in event_routes:
print(event_route)
```
### Delete event routes
Delete an event route given event route Id.
```Python Snippet:dt_scenario
service_client.delete_event_route(event_route_id)
```
### Publish telemetry messages for a digital twin
To publish a telemetry message for a digital twin, you need to provide the digital twin Id, along with the payload on which telemetry that needs the update.
```Python Snippet:dt_publish_telemetry
digita_twin_id = "<DIGITAL TWIN ID>"
telemetry_payload = '{"Telemetry1": 5}'
service_client.publish_telemetry(
digita_twin_id,
telemetry_payload
)
```
You can also publish a telemetry message for a specific component in a digital twin. In addition to the digital twin Id and payload, you need to specify the target component Id.
```Python Snippet:dt_publish_component_telemetry
digita_twin_id = "<DIGITAL TWIN ID>"
component_name = "<COMPONENT_NAME>"
telemetry_payload = '{"Telemetry1": 5}'
service_client.publish_component_telemetry(
digita_twin_id,
component_name,
telemetry_payload
)
```
## Troubleshooting
## Logging
This library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.
Detailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the logging_enable keyword argument:
### Client level logging
```python Snippet:dt_digitaltwins_get.py
import sys
import logging
# Create logger
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
# Create service client and enable logging for all operations
service_client = DigitalTwinsClient(url, credential, logging_enable=True)
```
### Per-operation level logging
```python Snippet:dt_models_get.py
import sys
import logging
# Create logger
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
# Get model with logging enabled
model = service_client.get_model(model_id, logging_enable=True)
```
### Optional Configuration
Optional keyword arguments can be passed in at the client and per-operation level. The azure-core [reference documentation](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/latest/azure.core.html) describes available configurations for retries, logging, transport protocols, and more.
[azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity
[azure_identity_pypi]: https://pypi.org/project/azure-identity/
[default_cred_ref]: https://aka.ms/azsdk/python/identity/docs#azure.identity.DefaultAzureCredential
[pip]: https://pypi.org/project/pip/
## Next steps
### Provide Feedback
If you encounter bugs or have suggestions, please
[open an issue](https://github.com/Azure/azure-sdk-for-python/issues).
## Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
# Release History
## 1.2.0 (2022-05-31)
- GA release
## 1.2.0b1 (2022-03-31)
### Bugs Fixed
- Update `azure-core` dependency to avoid inconsistent dependencies from being installed.
### Other Changes
- Python 2.7 and 3.6 are no longer supported. Please use Python version 3.7 or later.
## 1.1.0 (2020-11-24)
- The is the GA release containing the following changes:
**API updates**
- Added etag and match_condition parameters to upsert_digital_twin and upsert_relationship APIs to support conditional operation.
- Renamed `EventRoute` model to `DigitalTwinsEventRoute`.
- Removed unsed `azure.digitaltwins.core.QueryResult` object.
- Renamed the `component_path` to `component_name`
- Renamed the `payload` parameter to `telemetry` and made `message_id` a keyword-only parameter.
**Bug Fixes**
- The `relationship` parameter in `DigitalTwinsClient.upsert_relationship` is required and has been amended accordingly.
- The `json_patch` parameter in `DigitalTwinsClient.update_relationship` is required and has been amended accordingly.
- Renamed `models` parameter to `dtdl_models` in `DigitalTwinsClient.create_models`. This is now required.
- The `dependencies_for` parameter in `DigitalTwinsClient.list_models` is optional and has been amended accordingly.
- Match condition parameters have been fixed. Where invalid match conditions are supplied, a `ValueError` will be raised.
- Fixed double await on async listing operations.
**Documentation**
- User Agent value updated according to guidelines.
- Updated JSON patch parameter typehints to `List[Dict[str, object]]`.
- Updated constructor credential typehint to `azure.core.credentials.TokenCredential`
- Samples and documentation updated.
## 1.0.0b1 (2020-10-31)
* Initial Release
Raw data
{
"_id": null,
"home_page": "https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/digitaltwins/azure-digitaltwins-core",
"name": "azure-digitaltwins-core",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": "",
"keywords": "",
"author": "Microsoft Corporation",
"author_email": "azure-digitaltwins-core@microsoft.com",
"download_url": "https://files.pythonhosted.org/packages/38/59/683c7b1722e0f6090b2d11ea7ed721d398be684d445168e3c107dbc3bb2e/azure-digitaltwins-core-1.2.0.zip",
"platform": null,
"description": "# Azure Azure Digital Twins Core client library for Python\n\nThis package contains an SDK for Azure Digital Twins API to provide access to the Azure Digital Twins service for managing twins, models, relationships, etc.\n\n## _Disclaimer_\n\n_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_\n\n## Getting started\n\n### Introduction\n\nAzure Digital Twins is a developer platform for next-generation IoT solutions that lets you create, run, and manage digital representations of your business environment, securely and efficiently in the cloud. With Azure Digital Twins, creating live operational state representations is quick and cost-effective, and digital representations stay current with real-time data from IoT and other data sources. If you are new to Azure Digital Twins and would like to learn more about the platform, please make sure you check out the Azure Digital Twins [official documentation page](https://docs.microsoft.com/azure/digital-twins/overview).\n\nFor an introduction on how to program against the Azure Digital Twins service, visit the [coding tutorial page](https://docs.microsoft.com/azure/digital-twins/tutorial-code) for an easy step-by-step guide. Visit [this tutorial](https://docs.microsoft.com/azure/digital-twins/tutorial-command-line-app) to learn how to interact with an Azure Digital Twin instance using a command-line client application. Finally, for a quick guide on how to build an end-to-end Azure Digital Twins solution that is driven by live data from your environment, make sure you check out [this helpful guide](https://docs.microsoft.com/azure/digital-twins/tutorial-end-to-end).\n\nThe guides mentioned above can help you get started with key elements of Azure Digital Twins, such as creating Azure Digital Twins instances, models, twin graphs, etc. Use this samples guide below to familiarize yourself with the various APIs that help you program against Azure Digital Twins.\n\n### How to Install\n\nInstall [azure-digitaltwins-core][pypi_package_keys] and\n[azure-identity][azure_identity_pypi] with [pip][pip]:\n```Bash\npip install azure-digitaltwins-core azure-identity\n```\n[azure-identity][azure_identity] is used for Azure Active Directory\nauthentication as demonstrated below.\n\n### How to use\n\n#### Authentication, permission\n\nTo create a new digital twins client, you need the endpoint to an Azure Digital Twin instance and credentials.\nFor the samples below, the `AZURE_URL`, `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` environment variables have to be set.\nThe client requires an instance of [TokenCredential](https://docs.microsoft.com/dotnet/api/azure.core.tokencredential?view=azure-dotnet) or [ServiceClientCredentials](https://docs.microsoft.com/dotnet/api/microsoft.rest.serviceclientcredentials?view=azure-dotnet).\nIn this samples, we illustrate how to use one derived class: [DefaultAzureCredentials](https://docs.microsoft.com/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet).\n\n> Note: In order to access the data plane for the Digital Twins service, the entity must be given permissions.\n> To do this, use the Azure CLI command: `az dt rbac assign-role --assignee '<user-email | application-id>' --role owner -n '<your-digital-twins-instance>'`\n\nDefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.\nIt attempts to use multiple credential types in an order until it finds a working credential.\n\n##### Sample code\n\n```python Snippet:dt_create_digitaltwins_service_client.py\n# DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.\n# It attempts to use multiple credential types in an order until it finds a working credential.\n\n# - AZURE_URL: The URL to the ADT in Azure\nurl = os.getenv(\"AZURE_URL\")\n\n# DefaultAzureCredential expects the following three environment variables:\n# - AZURE_TENANT_ID: The tenant ID in Azure Active Directory\n# - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant\n# - AZURE_CLIENT_SECRET: The client secret for the registered application\ncredential = DefaultAzureCredential()\nservice_client = DigitalTwinsClient(url, credential)\n```\n\n## Key concepts\n\nAzure Digital Twins is an Azure IoT service that creates comprehensive models of the physical environment. It can create spatial intelligence graphs to model the relationships and interactions between people, spaces, and devices.\nYou can learn more about Azure Digital Twins by visiting [Azure Digital Twins Documentation](https://docs.microsoft.com/azure/digital-twins/).\n\n## Examples\n\nYou can explore the digital twins APIs (using the client library) using the samples project.\n\nThe samples project demonstrates the following:\n\n- Instantiate the client\n- Create, get, and decommission models\n- Create, query, and delete a digital twin\n- Get and update components for a digital twin\n- Create, get, and delete relationships between digital twins\n- Create, get, and delete event routes for digital twin\n- Publish telemetry messages to a digital twin and digital twin component\n\n### Create, list, decommission, and delete models\n\n#### Create models\n\nLet's create models using the code below. You need to pass an array containing list of models.\n\n```Python Snippet:dt_models_lifecycle\ntemporary_component = {\n \"@id\": component_id,\n \"@type\": \"Interface\",\n \"@context\": \"dtmi:dtdl:context;2\",\n \"displayName\": \"Component1\",\n \"contents\": [\n {\n \"@type\": \"Property\",\n \"name\": \"ComponentProp1\",\n \"schema\": \"string\"\n },\n {\n \"@type\": \"Telemetry\",\n \"name\": \"ComponentTelemetry1\",\n \"schema\": \"integer\"\n }\n ]\n}\n\ntemporary_model = {\n \"@id\": model_id,\n \"@type\": \"Interface\",\n \"@context\": \"dtmi:dtdl:context;2\",\n \"displayName\": \"TempModel\",\n \"contents\": [\n {\n \"@type\": \"Property\",\n \"name\": \"Prop1\",\n \"schema\": \"string\"\n },\n {\n \"@type\": \"Component\",\n \"name\": \"Component1\",\n \"schema\": component_id\n },\n {\n \"@type\": \"Telemetry\",\n \"name\": \"Telemetry1\",\n \"schema\": \"integer\"\n }\n ]\n}\n\nnew_models = [temporary_component, temporary_model]\nmodels = service_client.create_models(new_models)\nprint('Created Models:')\nprint(models)\n```\n\n### List models\nUsing `list_models` to retrieve all created models\n\n```Python Snippet:dt_models_lifecycle\nlisted_models = service_client.list_models()\nfor model in listed_models:\n print(model)\n```\n\n### Get model\nUse `get_model` with model's unique identifier to get a specific model.\n\n```Python Snippet:dt_models_lifecycle\n# Get a model\nget_model = service_client.get_model(model_id)\nprint('Get Model:')\nprint(get_model)\n```\n\n### Decommission model\nTo decommision a model, pass in a model Id for the model you want to decommision.\n\n```Python Snippet:dt_models_lifecycle\n# Decommission a model\nservice_client.decommission_model(model_id)\n```\n\n### Delete model\nTo delete a model, pass in a model Id for the model you want to delete.\n\n```Python Snippet:dt_models_lifecycle\n# Delete a model\nservice_client.delete_model(model_id)\n```\n\n## Create and delete digital twins\n\n### Create digital twins\nFor Creating Twin you will need to provide Id of a digital Twin such as `my_twin` and the application/json digital twin based on the model created earlier. You can look at sample application/json [here](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/digitaltwins/azure-digitaltwins-core/samples/dtdl/digital_twins).\n\n```Python Snippet:dt_digitaltwins_lifecycle\ndigital_twin_id = 'digitalTwin-' + str(uuid.uuid4())\ntemporary_twin = {\n \"$metadata\": {\n \"$model\": model_id\n },\n \"$dtId\": digital_twin_id,\n \"Prop1\": 42\n}\n\ncreated_twin = service_client.upsert_digital_twin(digital_twin_id, temporary_twin)\nprint('Created Digital Twin:')\nprint(created_twin)\n```\n\n### Get a digital twin\n\nGetting a digital twin is extremely easy.\n```Python Snippet:dt_digitaltwins_lifecycle\nget_twin = service_client.get_digital_twin(digital_twin_id)\nprint('Get Digital Twin:')\nprint(get_twin)\n```\n\n### Query digital twins\n\nQuery the Azure Digital Twins instance for digital twins using the [Azure Digital Twins Query Store lanaguage](https://docs.microsoft.com/azure/digital-twins/concepts-query-language). Query calls support paging. Here's an example of how to query for digital twins and how to iterate over the results.\n\nNote that there may be a delay between before changes in your instance are reflected in queries.\nFor more details on query limitations, see (https://docs.microsoft.com/azure/digital-twins/how-to-query-graph#query-limitations)\n\n```Python Snippet:dt_digitaltwins_query\nquery_expression = 'SELECT * FROM digitaltwins'\nquery_result = service_client.query_twins(query_expression)\nprint('DigitalTwins:')\nfor twin in query_result:\n print(twin)\n```\n\n### Delete digital twins\n\nDelete a digital twin simply by providing Id of a digital twin as below.\n\n```Python Snippet:dt_digitaltwins_lifecycle\nservice_client.delete_digital_twin(digital_twin_id)\n```\n\n## Get and update digital twin components\n\n### Update digital twin components\n\nTo update a component or in other words to replace, remove and/or add a component property or subproperty within Digital Twin, you would need Id of a digital twin, component name and application/json-patch+json operations to be performed on the specified digital twin's component. Here is the sample code on how to do it.\n\n```Python Snippet:dt_component_lifecycle\ncomponent_name = \"Component1\"\npatch = [\n {\n \"op\": \"replace\",\n \"path\": \"/ComponentProp1\",\n \"value\": \"value2\"\n }\n]\nservice_client.update_component(digital_twin_id, component_name, patch)\n```\n\n### Get digital twin components\n\nGet a component by providing name of a component and Id of digital twin to which it belongs.\n\n```Python Snippet:dt_component_lifecycle\nget_component = service_client.get_component(digital_twin_id, component_name)\nprint('Get Component:')\nprint(get_component)\n```\n\n## Create and list digital twin relationships\n\n### Create digital twin relationships\n\n`upsert_relationship` creates a relationship on a digital twin provided with Id of a digital twin, name of relationship such as \"contains\", Id of an relationship such as \"FloorContainsRoom\" and an application/json relationship to be created. Must contain property with key \"\\$targetId\" to specify the target of the relationship. Sample payloads for relationships can be found [here](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/digitaltwins/azure-digitaltwins-core/samples/dtdl/relationships/hospitalRelationships.json).\n\n```Python Snippet:dt_scenario\nhospital_relationships = [\n {\n \"$relationshipId\": \"BuildingHasFloor\",\n \"$sourceId\": building_twin_id,\n \"$relationshipName\": \"has\",\n \"$targetId\": floor_twin_id,\n \"isAccessRestricted\": False\n },\n {\n \"$relationshipId\": \"BuildingIsEquippedWithHVAC\",\n \"$sourceId\": building_twin_id,\n \"$relationshipName\": \"isEquippedWith\",\n \"$targetId\": hvac_twin_id\n },\n {\n \"$relationshipId\": \"HVACCoolsFloor\",\n \"$sourceId\": hvac_twin_id,\n \"$relationshipName\": \"controlsTemperature\",\n \"$targetId\": floor_twin_id\n },\n {\n \"$relationshipId\": \"FloorContainsRoom\",\n \"$sourceId\": floor_twin_id,\n \"$relationshipName\": \"contains\",\n \"$targetId\": room_twin_id\n }\n]\n\nfor relationship in hospital_relationships:\n service_client.upsert_relationship(\n relationship[\"$sourceId\"],\n relationship[\"$relationshipId\"],\n relationship\n )\n```\n\n### List digital twin relationships\n\n`list_relationships` and `list_incoming_relationships` lists all the relationships and all incoming relationships respectively of a digital twin.\n\n```Python Snippet:dt_relationships_list\nrelationships = service_client.list_relationships(digital_twint_id)\nfor relationship in relationships:\n print(relationship)\n```\n\n```Python Snippet:dt_incoming_relationships_list\nincoming_relationships = service_client.list_incoming_relationships(digital_twin_id)\nfor incoming_relationship in incoming_relationships:\n print(incoming_relationship)\n```\n\n## Create, list, and delete event routes of digital twins\n\n### Create event routes\n\nTo create an event route, provide an Id of an event route such as \"myEventRouteId\" and event route data containing the endpoint and optional filter like the example shown below.\n\n```Python Snippet:dt_scenario\nevent_route_id = 'eventRoute-' + str(uuid.uuid4())\nevent_filter = \"$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'\"\nroute = DigitalTwinsEventRoute(\n endpoint_name=event_hub_endpoint_name,\n filter=event_filter\n)\nservice_client.upsert_event_route(event_route_id, route)\n```\n\nFor more information on the event route filter language, see the \"how to manage routes\" [filter events documentation](https://github.com/Azure/azure-digital-twins/blob/private-preview/Documentation/how-to-manage-routes.md#filter-events).\n\n### List event routes\n\nList a specific event route given event route Id or all event routes setting options with `list_event_routes`.\n\n```Python Snippet:dt_event_routes_list\nevent_routes = service_client.list_event_routes()\nfor event_route in event_routes:\n print(event_route)\n```\n\n### Delete event routes\n\nDelete an event route given event route Id.\n\n```Python Snippet:dt_scenario\nservice_client.delete_event_route(event_route_id)\n```\n\n### Publish telemetry messages for a digital twin\n\nTo publish a telemetry message for a digital twin, you need to provide the digital twin Id, along with the payload on which telemetry that needs the update.\n\n```Python Snippet:dt_publish_telemetry\ndigita_twin_id = \"<DIGITAL TWIN ID>\"\ntelemetry_payload = '{\"Telemetry1\": 5}'\nservice_client.publish_telemetry(\n digita_twin_id,\n telemetry_payload\n)\n```\n\nYou can also publish a telemetry message for a specific component in a digital twin. In addition to the digital twin Id and payload, you need to specify the target component Id.\n\n```Python Snippet:dt_publish_component_telemetry\ndigita_twin_id = \"<DIGITAL TWIN ID>\"\ncomponent_name = \"<COMPONENT_NAME>\"\ntelemetry_payload = '{\"Telemetry1\": 5}'\nservice_client.publish_component_telemetry(\n digita_twin_id,\n component_name,\n telemetry_payload\n)\n```\n\n## Troubleshooting\n\n## Logging\nThis library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.\n\nDetailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the logging_enable keyword argument:\n\n### Client level logging\n```python Snippet:dt_digitaltwins_get.py\nimport sys\nimport logging\n\n# Create logger\nlogger = logging.getLogger('azure')\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(stream=sys.stdout)\nlogger.addHandler(handler)\n\n# Create service client and enable logging for all operations\nservice_client = DigitalTwinsClient(url, credential, logging_enable=True)\n```\n\n### Per-operation level logging\n```python Snippet:dt_models_get.py\nimport sys\nimport logging\n\n# Create logger\nlogger = logging.getLogger('azure')\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(stream=sys.stdout)\nlogger.addHandler(handler)\n\n# Get model with logging enabled\nmodel = service_client.get_model(model_id, logging_enable=True)\n```\n\n### Optional Configuration\nOptional keyword arguments can be passed in at the client and per-operation level. The azure-core [reference documentation](https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/latest/azure.core.html) describes available configurations for retries, logging, transport protocols, and more.\n\n[azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity\n[azure_identity_pypi]: https://pypi.org/project/azure-identity/\n[default_cred_ref]: https://aka.ms/azsdk/python/identity/docs#azure.identity.DefaultAzureCredential\n[pip]: https://pypi.org/project/pip/\n\n\n## Next steps\n\n### Provide Feedback\n\nIf you encounter bugs or have suggestions, please\n[open an issue](https://github.com/Azure/azure-sdk-for-python/issues).\n\n## Contributing\n\nThis project welcomes contributions and suggestions. Most contributions require you to agree to a\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\nthe rights to use your contribution. For details, visit https://cla.microsoft.com.\n\nWhen you submit a pull request, a CLA-bot will automatically determine whether you need to provide\na CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions\nprovided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\ncontact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\n\n# Release History\n\n## 1.2.0 (2022-05-31)\n - GA release\n\n## 1.2.0b1 (2022-03-31)\n\n### Bugs Fixed\n\n- Update `azure-core` dependency to avoid inconsistent dependencies from being installed.\n\n### Other Changes\n\n- Python 2.7 and 3.6 are no longer supported. Please use Python version 3.7 or later.\n\n\n## 1.1.0 (2020-11-24)\n\n- The is the GA release containing the following changes:\n\n**API updates**\n- Added etag and match_condition parameters to upsert_digital_twin and upsert_relationship APIs to support conditional operation.\n- Renamed `EventRoute` model to `DigitalTwinsEventRoute`.\n- Removed unsed `azure.digitaltwins.core.QueryResult` object.\n- Renamed the `component_path` to `component_name`\n- Renamed the `payload` parameter to `telemetry` and made `message_id` a keyword-only parameter.\n\n**Bug Fixes**\n- The `relationship` parameter in `DigitalTwinsClient.upsert_relationship` is required and has been amended accordingly.\n- The `json_patch` parameter in `DigitalTwinsClient.update_relationship` is required and has been amended accordingly.\n- Renamed `models` parameter to `dtdl_models` in `DigitalTwinsClient.create_models`. This is now required.\n- The `dependencies_for` parameter in `DigitalTwinsClient.list_models` is optional and has been amended accordingly.\n- Match condition parameters have been fixed. Where invalid match conditions are supplied, a `ValueError` will be raised.\n- Fixed double await on async listing operations.\n\n**Documentation**\n- User Agent value updated according to guidelines.\n- Updated JSON patch parameter typehints to `List[Dict[str, object]]`.\n- Updated constructor credential typehint to `azure.core.credentials.TokenCredential`\n- Samples and documentation updated. \n\n\n## 1.0.0b1 (2020-10-31)\n\n* Initial Release\n\n\n",
"bugtrack_url": null,
"license": "MIT License",
"summary": "Microsoft Azure Azure DigitalTwins Core Client Library for Python",
"version": "1.2.0",
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"md5": "575806f71764f5846ebaa5e3a454a10a",
"sha256": "f561995873e9b4beed0d3a66fef70abcda96a277ea72c4e85d277b9cc7eed7ae"
},
"downloads": -1,
"filename": "azure_digitaltwins_core-1.2.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "575806f71764f5846ebaa5e3a454a10a",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 69460,
"upload_time": "2022-07-12T17:52:22",
"upload_time_iso_8601": "2022-07-12T17:52:22.986399Z",
"url": "https://files.pythonhosted.org/packages/a9/0e/221cb9d0dc1ce66c3a4e02eb1ab351df036d935f36ef597ce72589dd70f9/azure_digitaltwins_core-1.2.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"md5": "3f456427e34ad79245416a9c64092ddb",
"sha256": "607d5a2771dfbbd1ae79392bc9eb8b6d5b93bbaaa74fe14ca23ac2b25a0a3dce"
},
"downloads": -1,
"filename": "azure-digitaltwins-core-1.2.0.zip",
"has_sig": false,
"md5_digest": "3f456427e34ad79245416a9c64092ddb",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 138482,
"upload_time": "2022-07-12T17:52:25",
"upload_time_iso_8601": "2022-07-12T17:52:25.273136Z",
"url": "https://files.pythonhosted.org/packages/38/59/683c7b1722e0f6090b2d11ea7ed721d398be684d445168e3c107dbc3bb2e/azure-digitaltwins-core-1.2.0.zip",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2022-07-12 17:52:25",
"github": false,
"gitlab": false,
"bitbucket": false,
"lcname": "azure-digitaltwins-core"
}