Py.Cafe

maartenbreddels/

solara-bitcoin-price-tracker

Sharing state between multiple users/tabs

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
from typing import Union, cast
import solara
import traitlets
import asyncio
from anyio import to_thread
import httpx
import solara._stores
import logging

logger = logging.getLogger("app")


btc = solara.Reactive(solara._stores.SharedStore(cast(Union[float, None], None)))
clicks = solara.Reactive(solara._stores.SharedStore(0))

def increase_clicks():
    clicks.value += 1

async def fetch_price():
    while 1:
        await asyncio.sleep(1)
        try:
            async with httpx.AsyncClient() as client:
                url = "https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT"
                response = await client.get(url)
                btc.value = float(response.json()["price"])
                print("btc.value", btc.value)
        except Exception as e:
            logger.exception("error in fetch_price")

asyncio.create_task(fetch_price())



@solara.component
def Page():
    print("render btc.value", btc.value)
    # make this component update when clicks changes
    with solara.Card("BTC price"):
        # if we do not make it conditional, like:
        # solara.Preformatted(f"$ {btc.value:,}" if btc.value else "loading...")
        # it does not crash
        if btc.value is not None:
            solara.Preformatted(f"$ {btc.value:,}")
        else:
            solara.ProgressLinear()
    with solara.Card("Button clicks"):
        solara.Text(f"{clicks.value:,} clicks")
        with solara.CardActions():
            solara.Button("Increase", on_click=increase_clicks, text=True)

requirements.txt
1
2
3
4
solara==1.43.0
https://py.cafe/gh/artifact/widgetti/solara/actions/runs/12482477896/solara-builds/solara-1.43.0-py2.py3-none-any.whl
https://py.cafe/gh/artifact/widgetti/solara/actions/runs/12482477896/solara-builds/solara_ui-1.43.0-py2.py3-none-any.whl
httpx