Skip to main content
Solved

Python SDK

  • 28 June 2024
  • 5 replies
  • 49 views

Hello:
Please share some code example in python sdk to link a file to an asset.

thanks

5 replies

Userlevel 4
Badge +7
from cognite.client import CogniteClient

# Initialize the CogniteClient
client = CogniteClient(api_key="your_api_key", project="your_project")

# Define the asset ID and the file ID
asset_id = 123456789
file_id = 987654321

# Link the file to the asset
client.files.update(id=file_id, asset_ids=[asset_id])

print(f"File with ID {file_id} linked to asset with ID {asset_id}.")

This represents the metadata for a file. It does not contain the actual file itself. This is the read-only version of FileMetadata and is used when retrieving data from CDF.

I haven't had time to test it, but based on the documentation, it should work. I will test it later, but if it works for you, let me know as well.

Userlevel 2
Badge +2

@Andre Alves thanks but it gives me the error:

TypeError: FilesAPI.update() got an unexpected keyword argument 'id'

and add the library:

from cognite.client.data_classes import FileMetadataUpdate

 

Userlevel 4
Badge +7

I did not have time to test it, but according to the Cognite documentation, you can use FileMetadataUpdate instead of updating directly as I mentioned before. Below is an example from the Cognite documentation on how to attach labels. In your case, you can replace labels with asset_ids as the parameter.

 

Attach labels to a files:

>>> from cognite.client import CogniteClient
>>> from cognite.client.data_classes import FileMetadataUpdate
>>> client = CogniteClient()
>>> my_update = FileMetadataUpdate(id=1).labels.add(["PUMP", "VERIFIED"])
>>> res = client.files.update(my_update)

 

The documentation is available here: https://cognite-sdk-python.readthedocs-hosted.com/en/latest/files.html

Userlevel 2
Badge +2

@Andre Alves 

Your last code worked well for me with the recommendations you give, thank you very much

Userlevel 4
Badge +7

Good to know! I hope you are doing well with your challenges. See you soon!

Reply