Home > Blockchain >  Passing a PyScript variable from one HTML page to another
Passing a PyScript variable from one HTML page to another

Time:01-28

I am trying to use a variable which I created using PyScript on one page in another page. This post initially seems to propose a solution, but when importing the variables, it turns out that they have been stored using (what I assume to be) their __repr__() function. That is obviously problematic for, among others, Pandas objects.

Page 1:

<py-script>
    # Code that generates these objects is omitted

    js.localStorage.setItem("dtypes", dtypes)
    js.localStorage.setItem("df", df)
    js.localStorage.setItem("target", target)
</py-script>

Page 2:

<py-script>
    import js

    dtypes = js.localStorage.getItem("dtypes")
    df = js.localStorage.getItem("df")
    target = js.localStorage.getItem("target")

    js.console.log(dtypes) # Returns the stored dictionary as a string
</py-script>

Is there a way to retain these variables as Python objects?

CodePudding user response:

It turns out that I misunderstood what setItem() and getItem() do. From the documentation, it follows that value must be a string (and otherwise will apparently be converted to a string representation).

Thus, my solution for storing Pandas DataFrames or Series is as follows, using to_csv without specifying the path_or_buf argument:

Page 1:

js.sessionStorage.setItem("df", df.to_csv()) 

Page 2:

df = js.sessionStorage.getItem("df")
df = io.StringIO(df)
df = pd.read_csv(df)
  • Related