Call C3 IoT from Python

#1

Did you know you can call C3 from your python implementation of C3 methods, just like you do in javascript?
Any python function is executed with a global c3 parameter containing a connection back to C3, so the line c3.FixedAsset.fetch(spec={"filter": ...}) in your Python method will return a dictionary object you can use in your code.

0 Likes

#2

To add to Louis’ comment: No need to import pyc3, the c3 variable is automatically available when running python implementations of C3 methods.

In general, the syntax needs to respect the API exactly. So for example, the documented signature for mergeBatch is mergeBatch(objs, spec) so the syntax for mergeBatch would be c3.FixedAsset.mergeBatch(objs=[...], spec={...}) and in the spec field use a dictionary with the MergeSpec fields as keys.

0 Likes

#3

I’m trying to do this:

c3.MyType.create(spec="{'message' : 'hello world'}")

But it doesn’t work. Have tried multiple variations. What am I doing wrong?

0 Likes

Upsert to an entity type directly from python function
#4

You do not need the quotes for the spec I think.

0 Likes

#5

That didn’t help.

This works in the console: MyType.create(spec={"message": "hello world"}) But I can’t figure out the Python equivalent.

0 Likes

#6

create is actually a member function so from Python it has to be called like this:

c3.MyType.create(c3.MyType(message = “hello world”))

the spec you are referring to is an UpsertSpec and would be a second argument (first argument if called as a member function). It controls the way the object is being upserted.

0 Likes

#7

No that doesn’t work. Neither does this:

c3.MyType.create(message = “hello world”)

or this

c3.MyType.create({'message': 'hello world'})

0 Likes

#8

You need to construct the object inside the create call: c3.MyType.create(c3.MyType(message = “hello world”))

0 Likes

#9

I had already tried that, and it doesn’t work. I did it exactly as suggested, substituting the actual type for MyType. It errors out with TypeError: 'C3Type' object is not callable. I have also experimented with numerous other ways to do this but can’t find a combination that actually works. The javascript example I posted above does work, so there is no problem with the type itself.

0 Likes

#10

Sorry for your trouble. For member functions with C3FastConnection I think you have to specify this=, eg if in Javascript you would do

MyType.create({message: “hello world”})

then in Python do

c3.MyType.create(this={“message”: “hello world”})

If that doesn’t work, could you please paste the code and error message you get?

0 Likes

#11

That did it! Thank you.

0 Likes