Py.Cafe

maartenbreddels/

generate-pycafe-link-with-files

Snippet Sharing Tool Demo (with files)

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import streamlit as st
from urllib.parse import quote, urlencode
import base64
import json
import gzip

code = """import streamlit as st
import pandas as pd

chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
st.area_chart(chart_data)
"""

requirements = """streamlit==1.27.2  # currently pinned to this version
altair
pandas
"""

files = [
    {
        "name": "some_file_loaded_from_a_url.py",
        # this file will be downloaded on the fly, this will keep the generated url short, and the content always up to date
        "url": "https://github.com/projectmesa/mesa-examples/raw/main/examples/virus_on_network/virus_on_network/model.py",
    },
    {
        "name": "other_file_from_data.py",
        # if content is provided, it's assumed to be text (utf8 encoded)
        "content": "plain text",
    },
    {
        "name": "binary_data.dat",
        # encode binary data in base64, but make sure to include the encoding
        "content": base64.b64encode(b"binary data").decode("utf8"),
        "encoding": "base64"
    }
]


json_object = {
    "code": code,
    "requirements": requirements,
    "files": files
}
json_text = json.dumps(json_object)
# compress using gzip to make the url shorter
compressed_json_text = gzip.compress(json_text.encode("utf8"))
# but encode in base64
base64_text = base64.b64encode(compressed_json_text).decode("utf8")
c = quote(base64_text)
# use the c= argument, c stands for compressed
url = f"https://py.cafe/snippet/streamlit/v1#c={c}"

st.link_button("Open snippet in new tab", url)
st.markdown(f"```\n{url}\n```")