DEV Community

artydev
artydev

Posted on

FastHTML : A simple Counter updated server side

Here is a demo of a server side incremented counter. Note the use of htmx

from fasthtml.common import *

app, rt = fast_app(hdrs=(picolink), live=True, live_reload=True)

@rt("/inc")
def get (session):
    session['sum'] = session.get('sum') + 1
    return session["sum"]

@rt("/")
def get(session):
    session.setdefault('sum', 0)
    return (
       Div (    
            Div (
                Button("inc", hx_get="/inc", hx_target="#counter"),
                Div(session["sum"], id="counter", cls="sum"),
                cls="counter"
            ),
           StyleX("style.css"),
           cls = "wrap-counter"
        )
    )

serve()
Enter fullscreen mode Exit fullscreen mode
.wrap-counter {
    background-color: white;
    display: flex;
    justify-content: space-around;
    margin-top: 4rem;
}

.counter {
    display:flex;
    align-items:center;
    gap:2rem;
}

.sum {
    font-size: 2rem;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

FastHTML integrates HTMX and make updating any part of a web page a breeeze, without making Ajax request.

Here is the same app as it it figures in the documentation. It does not use session variable:

from fasthtml.common import *

app, rt = fast_app(hdrs=(picolink), live=True, live_reload=True)

count = 0

@app.get("/")
def home():
    return Title("Count Demo"), Main(
        H1("Count Demo"),
        P(f"Count is set to {count}", id="count"),
        Button("Increment", hx_post="/increment", hx_target="#count", hx_swap="innerHTML")
    )

@app.post("/increment")
def increment():
    print("incrementing")
    global count
    count += 1
    return f"Count is set to {count}"

serve()
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay