Can we store pickled python objects in the anvil server session?

anvil.server.session can store anything that a server function can return, except for Media objects. This includes Data Table Rows.

I successfully store pickled object in a Data Table. Does the above imply that I can store a pickled object in the session?

1 Like

Not as a Media object, but possibly as a string.

I seem to remember you are serialising your objects to return from a server function, so you could store the serialised version.

I am storing it like this in the database record. I was wondering if it would work in the session object as well.

rdf_row['rdf']  = anvil.BlobMedia("bytes", pickle.dumps(rdf), "anvil.pickle")

It contains customer data that I am reluctant to leave in the database. So I thought it would be better as a session object.

So I am using the following to get my object into the session as a string:

    anvil.server.session["rdf"] = base64.b64encode(pickle.dumps(rdf)).decode('utf-8')

and I am recovering it like this:

    rdf_from_session = anvil.server.session['rdf']
    rdf_rehydrated = pickle.loads(base64.decodebytes(rdf_from_session.encode()))

It seems to fine. I am wondering what the performance overhead of this is? @shaun what do you think? Is there any issue with the size of the session object?

2 Likes

Might not be relevant to you, but be aware you can’t import pickle into the client yet (or you couldn’t last time I checked).

I am aware of this. My use case is simply to have a python object persistent through the session. I understand that only the database or the anvil session object has this capability.