Spaces:
Running
Running
Commit ·
ebec85b
0
Parent(s):
First version
Browse filesFiles changed (19)
- .gitignoreAdded+4
- .vscode/launch.jsonAdded+15
- .vscode/settings.jsonAdded+39
- DockerfileAdded+19
- README.mdAdded+37
- public/img/bars.svgAdded
- pyproject.tomlAdded+28
- src/tutorial/_01_click_to_edit.pyAdded+59
- src/tutorial/_02_bulk_update.pyAdded+58
- src/tutorial/_03_click_to_load.pyAdded+45
- src/tutorial/_04_delete_row.pyAdded+80
- src/tutorial/_05_edit_row.pyAdded+107
- src/tutorial/_06_lazy_loading.pyAdded+43
- src/tutorial/_07_inline_validation.pyAdded+64
- src/tutorial/__init__.pyAdded+159
- tests/__init__.pyAdded+1
- tests/test_all.pyAdded+42
- tests/test_click_to_edit.pyAdded+23
- uv.lockAdded
1234.sesskey*.ipynb__pycache__.venv123456789101112131415{ "version": "0.2.0", "configurations": [ { "name": "Python: Debug Tests", "type": "debugpy", "request": "launch", "program": "${file}", "purpose": ["debug-test"], "console": "integratedTerminal", "justMyCode": false, "env": { "PYTEST_ADDOPTS": "--no-cov" } } ]}123456789101112131415161718192021222324252627282930313233343536373839{ "[python]": { "editor.formatOnSave": true, "editor.defaultFormatter": "charliermarsh.ruff", "editor.codeActionsOnSave": { "source.fixAll": "explicit", "source.organizeImports": "explicit" } }, "notebook.formatOnSave.enabled": true, "notebook.codeActionsOnSave": { // "notebook.source.fixAll": "explicit", // "notebook.source.organizeImports": "explicit" }, "jupyter.debugJustMyCode": false, "python.testing.pytestArgs": ["tests"], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "files.exclude": { "**/*.egg-info": true, "**/htmlcov": true, "**/~$*": true, "**/.coverage.*": true, "**/.venv": true }, "python.analysis.autoFormatStrings": true,
"tailwindCSS.experimental.configFile": null, "tailwindCSS.classAttributes": [ "class", "className", "ngClass", "class:list", "cls" ], "tailwindCSS.includeLanguages": { "python": "html" }}12345678910111213141516171819FROM python:3.11-slimCOPY --chown=user --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
RUN useradd -m -u 1000 userUSER userWORKDIR /app
ADD uv.lock /app/uv.lockADD pyproject.toml /app/pyproject.toml
RUN uv sync --frozen --no-install-project
COPY --chown=user src ./srcRUN touch README.md
RUN uv sync --frozen
CMD ["uv", "run", "start_tutorial"]12345678910111213141516171819202122232425262728293031323334353637---title: Htmx Examplesemoji: 🦀colorFrom: redcolorTo: greensdk: dockerpinned: falselicense: mitapp_port: 5001---
# Fasthtml Examples
The repository reproduces HTMX official [examples](https://htmx.org/examples/) in Python with [FastHTML](https://docs.fastht.ml/)
Visit the site [here](https://phihung-htmx-examples.hf.space)
Github: [link](https://github.com/phihung/fasthtml_examples)
Run
```bash# Localuv syncuv run start_tutorial
# Dockerdocker build -t htmx_examples .docker run --rm -p 5001:5001 -it htmx_examples```
## Dev
```bashuv syncuv run pytest```12345678910111213141516171819202122232425262728[project]name = "tutorial"version = "0.1.0"description = "Add your description here"readme = "README.md"requires-python = ">=3.11"dependencies = [ "python-fasthtml>=0.5.1",]
[project.scripts]start_tutorial = "tutorial:start"
[build-system]requires = ["hatchling"]build-backend = "hatchling.build"
[tool.uv]dev-dependencies = [ "ipykernel>=6.29.5", "pytest-cov>=5.0.0", "pytest>=8.3.2", "ruff>=0.6.3",]
[tool.ruff]line-length = 120target-version = "py311"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859from collections import namedtuple
from fasthtml.common import Button, Div, Form, Input, Label, P, fast_app
app, rt = fast_app()
Contact = namedtuple("Contact", ["name", "email"])current = Contact("Joe", "joe@blow.com")
@app.get("/contact/1")def get_contact(): return Div( Div(P(f"Name : {current.name}")), Div(P(f"Email : {current.email}")), Button("Click To Edit", hx_get="/contact/1/edit", cls="btn primary"), hx_target="this", hx_swap="outerHTML", cls="container", )
@app.get("/contact/1/edit")def contact_edit(): return Form( Div(Label("Name"), Input(type="text", name="name", value=current.name)), Div(Label("Email"), Input(type="email", name="email", value=current.email)), Button("Submit", cls="btn"), Button("Cancel", hx_get="/contact/1", cls="btn"), hx_put="/contact/1", hx_target="this", hx_swap="outerHTML", cls="container", )
@app.put("/contact/1")def put_contact(c: Contact): global current current = c return get_contact()
DESC = "Demonstrates inline editing of a data object"DOC = """The click to edit pattern provides a way to offer inline editing of all or part of a record without a page refresh.
- This pattern starts with a UI that shows the details of a contact. The div has a button that will get the editing UI for the contact from /contact/1/edit
::get_contact:: - This returns a form that can be used to edit the contact
::contact_edit::
The form issues a PUT back to /contact/1, following the usual REST-ful pattern.
::put_contact::"""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from fasthtml.common import Button, Div, Form, Input, Style, Table, Tbody, Td, Th, Thead, Tr, fast_app
css = """\#toast.htmx-settling { opacity: 100;}
#toast { opacity: 0; transition: opacity 3s ease-out; background: blue; color: orange;}"""
app, rt = fast_app(hdrs=[Style(css)])
@app.get("/users")def list_users(): return Form( Table( Thead(Tr(Th("Name"), Th("Email"), Th("Active"))), Tbody( Tr(Td("Kim 1"), Td("kim@1.org"), Td(Input(type="checkbox", name="active:kim@1.org"))), Tr(Td("Kim 2"), Td("kim@2.org"), Td(Input(type="checkbox", name="active:kim@2.org"))), Tr(Td("Kim 3"), Td("kim@3.org"), Td(Input(type="checkbox", name="active:kim@3.org"))), Tr(Td("Kim 4"), Td("kim@4.org"), Td(Input(type="checkbox", name="active:kim@4.org"))), ), ), Button("Bulk Update", cls="btn primary"), Div(id="toast"), # Bug with default enctype: multipart/form-data enctype="", hx_post="/users", hx_swap="outerHTML settle:3s", hx_target="#toast", cls="container", )
@app.post("/users")def bulk_update(x: dict): n = len(x) return Div(f"Activated {n} and deactivated {4-n} users", id="toast", aria_live="polite")
DESC = "Demonstrates bulk updating of multiple rows of data"DOC = """This demo shows how to implement a common pattern where rows are selected and then bulk updated. This is accomplished by putting a form around a table, with checkboxes in the table, and then including the checked values in the form submission (POST request):
The server will bulk-update the statuses based on the values of the checkboxes. We respond with a small toast message about the update to inform the user, and use ARIA to politely announce the update for accessibility.::css::The cool thing is that, because HTML form inputs already manage their own state, we don’t need to re-render any part of the users table. The active users are already checked and the inactive ones unchecked!
You can see a working example of this code below.::list_users bulk_update::"""123456789101112131415161718192021222324252627282930313233343536373839404142434445from fasthtml.common import Button, Div, Table, Tbody, Td, Th, Thead, Tr, fast_app
app, rt = fast_app()
# fmt: off@app.get("/table")def contact_table(): return Div( Table( Thead(Tr(Th("Name"), Th("ID"))), Tbody(load_contacts(page=1)), ), cls="container overflow-auto", )# fmt: on
@app.get("/contacts")def load_contacts(page: int, limit: int = 5): rows = [Tr(Td("Smith"), Td(page * limit + i)) for i in range(limit)] return *rows, make_last_row(page)
def make_last_row(page): return Tr( Td( Button( "Load More Agents...", hx_get=f"/contacts?page={page + 1}", hx_swap="outerHTML", cls="btn primary", ), colspan="3", ), hx_target="this", )
DESC = "Demonstrates clicking to load more rows in a table"DOC = """This example shows how to implement click-to-load the next page in a table of data. The crux of the demo is the final row:::make_last_row load_contacts::This row contains a button that will replace the entire row with the next page of results (which will contain a button to load the next page of results). And so on."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980from fasthtml.common import Button, Div, Style, Table, Tbody, Td, Th, Thead, Tr, fast_app
css = """\tr.htmx-swapping td { opacity: 0; transition: opacity 1s ease-out;}"""
app, rt = fast_app(hdrs=[Style(css)])
@app.get("/table")def contact_table(): return Div( Table( Thead(Tr(Th("Name"), Th("Email"), Th())), Tbody( Tr( Td("Joe Smith"), Td("joe@smith.org"), Td(Button("Delete", hx_delete="/contacts/0", cls="btn danger")), ), Tr( Td("Angie MacDowell"), Td("angie@macdowell.org"), Td(Button("Delete", hx_delete="/contacts/1", cls="btn danger")), ), Tr( Td("Fuqua Tarkenton"), Td("fuqua@tarkenton.org"), Td(Button("Delete", hx_delete="/contacts/2", cls="btn danger")), ), Tr( Td("Kim Yee"), Td("kim@yee.org"), Td(Button("Delete", hx_delete="/contacts/3", cls="btn danger")), ), hx_confirm="Are you sure?", hx_target="closest tr", hx_swap="outerHTML swap:1s", ), ), cls="container overflow-auto", )
@app.delete("/contacts/{idx}")def delete_contact(idx: int): # Delete actual data here return None
DESC = "Demonstrates row deletion in a table"DOC = """This example shows how to implement a delete button that removes a table row upon completion. First let’s look at the table body:```pythonTable( Thead(), Tbody( Tr(), Tr(), Tr(), Tr(), hx_confirm="Are you sure?", hx_target="closest tr", hx_swap="outerHTML swap:1s", ))```The table body has a `hx-confirm` attribute to confirm the delete action. It also set the target to be the closest tr that is, the closest table row, for all the buttons (hx-target is inherited from parents in the DOM.) The swap specification in hx-swap says to swap the entire target out and to wait 1 second after receiving a response. This last bit is so that we can use the following CSS:::css::To fade the row out before it is swapped/removed.
Each row has a button with a hx-delete attribute containing the url on which to issue a DELETE request to delete the row from the server. This request responds with a 200 status code and empty content, indicating that the row should be replaced with nothing.```pythonTr( Td("Angie MacDowell"), Td("angie@macdowell.org"), Td(Button("Delete", hx_delete="/contacts/1", cls="btn danger")),)```"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107from fasthtml.common import Button, Div, Input, Table, Tbody, Td, Th, Thead, Tr, fast_app
app, rt = fast_app()
DATA = [ ("Joe 1", "joe1@a.b"), ("Joe 2", "joe2@a.b"), ("Joe 3", "joe3@a.b"), ("Joe 4", "joe4@a.b"),]
@app.get("/table")def contact_table(): return Div( Table( Thead(Tr(Th("Name"), Th("Email"), Th())), Tbody( *(get_contact(i) for i in range(4)), hx_target="closest tr", hx_swap="outerHTML", ), ), cls="container-fluid", )
@app.get("/contact/{idx}/edit")def edit_contact(idx: int): name, email = DATA[idx] return Tr( Td(Input(name="name", value=name)), Td(Input(name="email", value=email)), Td( Button("Cancel", hx_get=f"/contact/{idx}", cls="btn secondary"), Button("Save", hx_put=f"/contact/{idx}", hx_include="closest tr", cls="btn primary"), ), hx_trigger="cancel", hx_get=f"/contact/{idx}", cls="editing", )
@app.get("/contact/{idx}")def get_contact(idx: int): name, email = DATA[idx] return Tr( Td(name), Td(email), Td(Button("Edit", hx_get=f"/contact/{idx}/edit", hx_trigger="edit", onclick=JS)), )
@app.put("/contact/{idx}")def put_contact(idx: int, x: dict): DATA[idx] = (x["name"], x["email"]) return get_contact(idx)
JS = """let editing = document.querySelector('.editing')if(editing) { htmx.trigger(editing, 'cancel');}htmx.trigger(this, 'edit')"""
# JS = """# let editing = document.querySelector('.editing')# if(editing) {# Swal.fire({# title: 'Already Editing',# showCancelButton: true,# confirmButtonText: 'Yep, Edit This Row!',# text:'Hey! You are already editing a row! Do you want to cancel that edit and continue?'# })# .then((result) => {# if(result.isConfirmed) {# htmx.trigger(editing, 'cancel')# htmx.trigger(this, 'edit')# }# })# } else {# htmx.trigger(this, 'edit')# }# """
DESC = "Demonstrates how to edit rows in a table"DOC = """This example shows how to implement editable rows. First let’s look at the table body:::contact_table::This will tell the requests from within the table to target the closest enclosing row that the request is triggered on and to replace the entire row.
Here is the HTML for a row:::get_contact::Javascript code::JS::Here we are getting a bit fancy and only allowing one row at a time to be edited, using some JavaScript. We check to see if there is a row with the .editing class on it and confirm that the user wants to edit this row and dismiss the other one. If so, we send a cancel event to the other row so it will issue a request to go back to its initial state.
We then trigger the edit event on the current element, which triggers the htmx request to get the editable version of the row.
Note that if you didn’t care if a user was editing multiple rows, you could omit the hyperscript and custom hx-trigger, and just let the normal click handling work with htmx. You could also implement mutual exclusivity by simply targeting the entire table when the Edit button was clicked. Here we wanted to show how to integrate htmx and JavaScript to solve the problem and narrow down the server interactions a bit, plus we get to use a nice SweetAlert confirm dialog.
Finally, here is what the row looks like when the data is being edited:::edit_contact::Here we have a few things going on: First off the row itself can respond to the cancel event, which will bring back the read-only version of the row. There is a cancel button that allows cancelling the current edit. Finally, there is a save button that issues a PUT to update the contact. Note that there is an hx-include that includes all the inputs in the closest row. Tables rows are notoriously difficult to use with forms due to HTML constraints (you can’t put a form directly inside a tr) so this makes things a bit nicer to deal with."""12345678910111213141516171819202122232425262728293031323334353637383940414243import time
from fasthtml.common import Button, Div, Img, NotStr, Style, fast_app
css = """.htmx-settling img { opacity: 0;}img { transition: opacity 300ms ease-in;}"""
app, rt = fast_app(hdrs=[Style(css)])
@app.get("/page")def main_page(): return Div( Img(src="/img/bars.svg", alt="Result loading...", cls="htmx-indicator", width="150"), hx_get="/content", hx_trigger="load", cls="container", )
@app.get("/content")def get_graph(): time.sleep(3) return Div( NotStr("<ins>This simple text takes 3s to load!</ins>"), Button("Reload", hx_target="body", hx_get="/page"), )
DESC = "Demonstrates how to lazy load content"HTMX_URL = "https://htmx.org/examples/lazy-load/"DOC = """This example shows how to lazily load an element on a page. We start with an initial state that looks like this:::main_page::Which shows a progress indicator as we are loading the graph. The graph is then loaded and faded gently into view via a settling CSS transition:::css::"""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import time
from fasthtml.common import H3, Button, Div, Form, Img, Input, Label, NotStr, Span, Style, fast_app
css = """.error input { box-shadow: 0 0 3px #CC0000;}.valid input { box-shadow: 0 0 3px #36cc00;}"""
app, rt = fast_app(hdrs=[Style(css)])
@app.get("/form")def main_page(): return Div( H3("Signup Form"), NotStr( "Enter an email into the input below and on tab out it will be validated. Only <ins>test@test.com</ins> will pass." ), Form( make_email_field("", error=False, touched=False), Div(Label("Name"), Input(name="name")), Button("Submit", disabled="", cls="btn primary"), ), cls="container", )
@app.post("/contact/email")def validate_email(email: str): time.sleep(2) return make_email_field(email, email != "test@test.com", True)
def make_email_field(value: str, error: bool, touched: bool): return Div( Label("Email"), Input(name="email", hx_post="/contact/email", hx_indicator="#ind", value=value), Img(id="ind", src="/img/bars.svg", cls="htmx-indicator"), Span("Please enter a valid email address", style="color:red;") if error else None, hx_target="this", hx_swap="outerHTML", cls="" if not touched else "error" if error else "valid", )
DESC = "Demonstrates how to do inline field validation"DOC = """This example shows how to do inline field validation, in this case of an email address. To do this we need to create a form with an input that POSTs back to the server with the value to be validated and updates the DOM with the validation results.
We start with this form:::main_page make_email_field::
Note that the email div in the form has set itself as the target of the request and specified the outerHTML swap strategy, so it will be replaced entirely by the response. The input then specifies that it will POST to /contact/email for validation, when the changed event occurs (this is the default for inputs). It also specifies an indicator for the request.
When a request occurs, it will return a partial to replace the outer div. It might look like this:
This form can be lightly styled with this CSS to give better visual feedback.::css::"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159import importlibimport inspectimport refrom dataclasses import dataclassfrom functools import cached_propertyfrom pathlib import Pathfrom types import ModuleType
from fasthtml.common import ( H1, A, Code, Div, HighlightJS, Iframe, Main, MarkdownJS, P, Pre, Script, Table, Tbody, Td, Th, Thead, Tr, fast_app, serve,)
hdrs = ( MarkdownJS(), HighlightJS(langs=["python", "javascript", "html", "css"]),)app, rt = fast_app(hdrs=hdrs, static_path="public")
examples = sorted([f.stem for f in Path(__file__).parent.glob("*.py") if f.stem not in ["__init__"]])
@app.get("/")def homepage(): ls = [get_example(name) for name in examples] return Main( Table( Thead(Tr(Th("Pattern"), Th("Description"))), Tbody(tuple(Tr(Td(A(ex.title, href="/" + ex.slug)), Td(ex.desc)) for ex in ls)), ), cls="container", )
def get_app(): for name in examples: get_example(name).create_routes(app) return app
def get_example(name): module = importlib.import_module(f"tutorial.{name}") return Example(module, name[4:])
@dataclassclass Example: module: ModuleType name: str
@cached_property def title(self): return self.name.replace("_", " ").title()
@cached_property def desc(self): return self.module.DESC
@cached_property def doc(self): return self.module.DOC
@cached_property def slug(self): return self.name.replace("_", "-")
@cached_property def htmx_url(self): return getattr(self.module, "HTMX_URL", f"https://htmx.org/examples/{self.slug}/")
@cached_property def start_url(self): module, slug = self.module, self.slug url = getattr(module, "START_URL", module.app.routes[1].path) return f"/{slug}{url}"
def create_routes(self, app): module, slug = self.module, self.slug self._fix_url() app.mount(f"/{slug}", module.app) app.get(f"/{slug}")(self.main_page)
def main_page(self, tab: str = "explain"): module = self.module if tab == "code": code = Path(module.__file__).read_text().split("DESC = ")[0] code = code.strip().replace("# fmt: on\n", "").replace("# fmt: off\n", "") content = Pre(Code(code)) else: doc = re.sub("::([a-zA-Z_0-9\s]+)::", lambda x: code_block(module, x.group(1)), self.doc) content = Div(doc, cls="marked")
return Main( H1(self.title), Div( A("Back", href="/"), "|", A("Explain", href=f"/{self.slug}?tab=explain"), "|", A("Code", href=f"/{self.slug}?tab=code"), "|", A("Htmx Docs", href=self.htmx_url), ), Div( Div(content, style="height:80vh;overflow:scroll"), Div(P(A("Direct url", href=self.start_url)), Iframe(src=self.start_url, height="500px", width="100%")), cls="grid", ), cls="container", )
def _fix_url(self): module, slug = self.module, self.slug code = f""" document.addEventListener('htmx:configRequest', (event) => {{ event.detail.path = `/{slug}${{event.detail.path}}` }}) """ module.app.hdrs.append(Script(code))
def code_block(module, obj): code = "" for o in obj.strip().split(): func = getattr(module, o) if callable(func): func = getattr(func, "__wrapped__", func) code += inspect.getsource(func) else: code += str(func).strip() code += "\n" code = code.strip() return f"```\n{code.strip()}\n```"
def start(): print("hi") serve("tutorial.__init__", app="get_app")
if __name__ == "__main__": serve(app="get_app")1
123456789101112131415161718192021222324252627282930313233343536373839404142from pathlib import Path
import httpximport pytestfrom starlette.testclient import TestClient
from tutorial import get_app, get_example
EXAMPLES = [f.stem for f in Path("src/tutorial").glob("*.py") if f.stem not in ["__init__"]]
@pytest.mark.parametrize("example", EXAMPLES)def test_example_page(client, example): m = get_example(example) main_func = next(x for x in m.module.app.routes if m.start_url.endswith(x.path)).name
r = client.get(f"/{m.slug}") assert r.status_code == 200 assert m.module.DOC.strip().splitlines()[0] in r.text assert "::" not in r.text
r = client.get(f"/{m.slug}?tab=code") assert r.status_code == 200 assert m.module.DOC.strip().splitlines()[0] not in r.text assert f"def {main_func}" in r.text assert "app, rt = fast_app(" in r.text assert m.htmx_url in r.text assert httpx.head(m.htmx_url).status_code == 200
@pytest.mark.parametrize("example", EXAMPLES)def test_start_url(client, example): m = get_example(example) r = client.get(m.start_url) assert r.status_code == 200 print(r.text) assert "<html>" in r.text
@pytest.fixturedef client(): return TestClient(get_app())1234567891011121314151617181920212223from starlette.testclient import TestClient
from tutorial import _01_click_to_edit as module
def test_app(): client = TestClient(module.app)
def check(r): c = module.current assert r.status_code == 200 assert c.name in r.text assert c.email in r.text
r = client.get("/contact/1") check(r)
r = client.get("/contact/1/edit") check(r)
r = client.put("/contact/1", data={"name": "AAA", "email": "BB"}) check(r) assert module.current.name == "AAA".gitignoreAdded+4
.vscode/launch.jsonAdded+15
.vscode/settings.jsonAdded+39
DockerfileAdded+19
README.mdAdded+37
public/img/bars.svgAdded
pyproject.tomlAdded+28
src/tutorial/_01_click_to_edit.pyAdded+59
src/tutorial/_02_bulk_update.pyAdded+58
src/tutorial/_03_click_to_load.pyAdded+45
src/tutorial/_04_delete_row.pyAdded+80
src/tutorial/_05_edit_row.pyAdded+107
src/tutorial/_06_lazy_loading.pyAdded+43
src/tutorial/_07_inline_validation.pyAdded+64
src/tutorial/__init__.pyAdded+159
tests/__init__.pyAdded+1
tests/test_all.pyAdded+42
tests/test_click_to_edit.pyAdded+23
uv.lockAdded