Py.Cafe

maartenbreddels/

solara-cancel-task

Solara Interactive Data Fetcher

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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 07:27:16 2024
@author: marik
"""

import time
import solara
import asyncio
from solara.lab import task
import logging

logger = logging.getLogger("tasks")
logger.setLevel(logging.INFO)

number_of_runs = 0

@task
async def fetch_data():
    global number_of_runs
    print(f"fetch_data started, is_current is {fetch_data.is_current()}")
    await asyncio.sleep(2)
    print(f"fetch_data stopped sleeping, is_current is {fetch_data.is_current()}")
    if not fetch_data.is_current():
        print("Trying to cancel")
        fetch_data.cancel()
        return
    number_of_runs = number_of_runs + 1
    print(f"fetch_data finished")
    return f"The answer is 42, # of runs is {number_of_runs}"


@solara.component
def Page():
    with solara.Card("Cancel task demo"):
        solara.Button("Fetch data", on_click=fetch_data)
        solara.ProgressLinear(fetch_data.pending)

        if fetch_data.finished:
            solara.Text(fetch_data.value)
        elif fetch_data.not_called:
            solara.Text("Click the button to fetch data")
        # Optional state check
        elif fetch_data.cancelled:
            solara.Text("Cancelled the fetch")
        elif fetch_data.error:
            solara.Error(str(fetch_data.exception))