from: Modern Web Apps in Pure Python - NeuralNine

Modern web applications in pure Python. Built on solid web foundations, not the latest fads - with FastHTML you can get started on anything from simple dashboards to scalable web applications in minutes.

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from fasthtml import common as fh


def render_person(person):
pid = f"person-{person.pid}"

delete_button = fh.A(
"Delete", hx_delete=f"people/{person.pid}", hx_swap="outerHTML", target_id=pid
)

return fh.Li(
delete_button,
f"Name: {person.name}, Age: {person.age}, Job: {person.job}",
id=pid,
)


app, rt, people, Person = fh.fast_app(
live=True,
db_file="data/people.db",
pid=int,
name=str,
age=int,
job=str,
pk="pid",
render=render_person,
)



def form_input():
return [
fh.Input(id="name", placeholder="Name", name="name", hx_swap_oob="true"),
fh.Input(
id="age", placeholder="Age", name="age", type="number", hx_swap_oob="true"
),
fh.Input(id="job", placeholder="Job", name="job", hx_swap_oob="true"),
]


def mock_person():
if len(people()) == 0:
people.insert(Person(name="Ben Parker", age=33, job="IT"))
people.insert(Person(name="Claudia Bashirian", age=40, job="IT"))


@rt("/people", methods=["get"])
def list_people():
mock_person()

create_form = fh.Form(
fh.Group(
*form_input(),
fh.Button("Create"),
),
hx_post="/people",
hx_swap="beforeend",
target_id="people_list",
)

return fh.Div(fh.Card(fh.Ul(*people(), id="people_list"), header=create_form))


@rt("/people", methods=["post"])
def create_person(person: Person): # type: ignore
return people.insert(person), *form_input()


@rt("/people/{pid}", methods=["delete"])
def delete_person(pid: int):
people.delete(pid)


@rt("/")
def index():
return fh.Titled(
"FastHTML App",
fh.Div(fh.P("Hello World")),
fh.A("FastHTML", href="https://fastht.ml/"),
fh.A("Hello", href="/hello"),
)


@rt("/hello")
def hello():
return fh.Div(fh.P("This is the hello page"), fh.A("Home", href="/"))

@rt("/fibonacci/{n}")
def fibonacci(n: int):
numbers = []

a, b = 0, 1
for _ in range(n):
numbers.append(a)
b, a = a, a + b

return fh.Titled("Fibonacci Numbers", fh.Ul(*[fh.Li(num) for num in numbers]))


fh.serve()
Edited on