Добавление отношений сущностей в Thingsboard с использованием swagger API и python

2

Я пытаюсь автоматизировать настройку узла Thingsboard. (2.0.2)

Мне удалось создать активы и устройства, используя пример oss-aboutboard-backend-example.

Однако мне не удалось создать отношения.

Используемый мной код

from tb_api_client import swagger_client
from tb_api_client.swagger_client import ApiClient, Configuration,Device,AssetControllerApi,AssetSearchQuery,Asset,EntityRelation,EntityRelationControllerApi
from tb_api_client.swagger_client.rest import ApiException

tojson = lambda x: json.loads(str(x).replace("None","'None'").replace("'",'"').replace("True","true").replace("False","false"))


# get the token. 
headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' }

token_response = requests.post('http://127.0.0.1:8080/api/auth/login',data=login,headers=headers)
token = json.loads(token_response.text)

        # set up the api-client. 

api_client_config                   = Configuration()
api_client_config.host              = '127.0.0.1:8080'
api_client_config.api_key['X-Authorization']    = 'Bearer %s' % token['token']
api_client                      = ApiClient(api_client_config)

device_controller_api       = swagger_client.DeviceControllerApi(api_client=api_client)
device_api_controller_api       = swagger_client.DeviceApiControllerApi(api_client=api_client)
asset_controller_api        = swagger_client.AssetControllerApi(api_client=api_client)
entity_relation_controller_api  = swagger_client.EntityRelationControllerApi(api_client=api_client)

dv = Device(name="A",type="Sensor1")            
newdevice_res = device_controller_api.save_device_using_post(dv)
devicedata = tojson(newdevice_res) 

# Get the new device id.
deviceid = devicedata['id']['id']

newAsset = Asset(name="B",type="Home") 
R,res,header = asset_controller_api.save_asset_using_post_with_http_info(newAsset)          
asset_res = tojson(R)
assetid = asset_res['id']['id']

Все идет нормально. Этот код создает актив и устройство, и у меня есть их идентификаторы.

Теперь я пытаюсь создать связь между ними:

newrelation = EntityRelation(_from=assetid,to=deviceid,type='Contains',type_group='COMMON')
print(newrelation)

Соотношение

{'_from': u'd4472320-73ca-11e8-9297-b93b0883b039 ',' дополнительная_info ': None,' to ': u'4fe6c710-7312-11e8-9297-b93b0883b039', 'type': 'Contains', ' type_group ':' COMMON '}

Но когда я пытаюсь его сохранить:

R,res,header = entity_relation_controller_api.save_relation_using_post(newrelation)
print(R)

И я получаю

Traceback (most recent call last):
  File "python/bin/LoadScenario.py", line 122, in <module>
    R,res,header = entity_relation_controller_api.save_relation_using_post(newrelation)
  File "/home/yehudaa/Projects/2018/GeshemBeito/python/tb_api_client/swagger_client/apis/entity_relation_controller_api.py", line 835, in save_relation_using_post
    (data) = self.save_relation_using_post_with_http_info(relation, **kwargs)
  File "/home/yehudaa/Projects/2018/GeshemBeito/python/tb_api_client/swagger_client/apis/entity_relation_controller_api.py", line 911, in save_relation_using_post_with_http_info
    collection_formats=collection_formats)
  File "/home/yehudaa/Projects/2018/GeshemBeito/python/tb_api_client/swagger_client/api_client.py", line 319, in call_api
    _return_http_data_only, collection_formats, _preload_content, _request_timeout)
  File "/home/yehudaa/Projects/2018/GeshemBeito/python/tb_api_client/swagger_client/api_client.py", line 153, in __call_api
    _request_timeout=_request_timeout)
  File "/home/yehudaa/Projects/2018/GeshemBeito/python/tb_api_client/swagger_client/api_client.py", line 362, in request
    body=body)
  File "/home/yehudaa/Projects/2018/GeshemBeito/python/tb_api_client/swagger_client/rest.py", line 262, in POST
    body=body)
  File "/home/yehudaa/Projects/2018/GeshemBeito/python/tb_api_client/swagger_client/rest.py", line 218, in request
    raise ApiException(http_resp=r)
tb_api_client.swagger_client.rest.ApiException: (400)
Reason: 
HTTP response headers: HTTPHeaderDict({'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Transfer-Encoding': 'chunked', 'Expires': '0', 'Connection': 'close', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate', 'Date': 'Tue, 19 Jun 2018 16:17:15 GMT', 'Content-Type': 'application/json;charset=UTF-8'})
HTTP response body: {"timestamp":1529425035915,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Could not read document: com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode (through reference chain: org.thingsboard.server.common.data.relation.EntityRelation[\"to\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode (through reference chain: org.thingsboard.server.common.data.relation.EntityRelation[\"to\"])","path":"/api/relation"}

Есть идеи?

Теги:
swagger
thingsboard

1 ответ

1

Тело отношения имеет вид:

{
  "from": {
    "id": "eb1a6dd0-73db-11e8-ba6f-5f195a167785",
    "entityType": "ASSET"
  },
  "type": "Contains",
  "to": {
    "entityType": "DEVICE",
    "id": "80131e70-745c-11e8-ba6f-5f195a167785"
  },
  "additionalInfo": null
}

Я создал JSON напрямую, а не с помощью EntityRelation, и он работает.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню