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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more