Skip to content

Instantly share code, notes, and snippets.

@vacmar01
Created April 2, 2025 17:52
Show Gist options
  • Save vacmar01/2b4c20c1218c86d4a19ae610657f9932 to your computer and use it in GitHub Desktop.
Save vacmar01/2b4c20c1218c86d4a19ae610657f9932 to your computer and use it in GitHub Desktop.
from fasthtml.common import *
from dataclasses import make_dataclass, fields
import datetime
from pathlib import Path
import yaml
def create_dataclass_from_schema(schema_dict, cls_name="DynamicClass"):
str2type = {
"str": str,
"int": int,
"bool": bool,
"float": float,
"list": list,
"tuple": tuple,
"dict": dict,
"set": set,
"path": Path,
"date": datetime.date,
}
fields = [(name, str2type[type_str]) for name, type_str in schema_dict.items()]
cls = make_dataclass(cls_name, fields)
return cls
def field2inp(f, value=None):
t2t = {str: "text", int: "number", datetime.date: "date", bool: "checkbox"}
inp = Input(
type=t2t.get(f.type, "text"),
value=value if f.type is not bool else None,
id=f.name,
required=f.type is not bool,
checked=f.type is bool and value,
)
return Label(f.name.capitalize(), fr=f.name), inp
config = yaml.safe_load(Path("schema.yaml").read_text(encoding="utf-8"))
user_schema = config["user"]
User = create_dataclass_from_schema(user_schema, "User")
app, rt = fast_app()
@rt('/')
def index():
u = User("John", 30, "1992-10-19")
return Main(cls="container")(
Form(action="#")(
*[
field2inp(f, getattr(u, f.name)) # or if you need an empty form, just field2inp(f)
for f in fields(User)
],
Button("Submit", type="submit")
)
)
serve()
user:
name: str
age: int
birthday: date
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment