简体   繁体   中英

Passing a PyScript variable from one HTML page to another

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM