Web Development
Building a Dynamic Social Wall with Flask and HTMX
Introduction
Most interactive web features, such as posting a message, adding a comment or liking a post, follow the same pattern: a user action triggers a JavaScript fetch, the server returns JSON, and JavaScript parses it and rewrites part of the page. That pattern needs a client-side rendering layer, state kept in the browser, and an API contract between frontend and backend that both sides must keep in sync. For a team that already renders its HTML on the server, this is often more machinery than the feature deserves.
HTMX removes most of that machinery. Instead of returning JSON and letting JavaScript rebuild the page, the server returns a ready-made piece of HTML, and HTMX inserts it at the spot the markup asks for. Flask handles the routing and produces the HTML; HTMX sends the request and does the insertion. In this tutorial we will build a team social wall where posts and comments appear instantly without a page reload, and we will not write a single line of JavaScript ourselves.
A few assumptions so that every command and path is exact:
- You are working in the Full-Stack Web Development sandbox on Bytestark.com.
- Your starting folder is
/home/coder/learning, and we createsocial_wall.pydirectly in it. That folder already contains astatic/directory with Bootstrap andhtmx.min.js, and Flask serves astatic/folder that sits next to the application file automatically, so the page can load both without any configuration. - You will open the running app on your sandbox URL and use
curlfrom a second terminal to see the exact HTML the server returns.
Background
HTMX is a JavaScript library loaded with a single <script> tag. It scans the page for hx-* attributes and, when an element with one of them is triggered, sends an HTTP request and swaps the response into the page. The library is the only JavaScript in this tutorial, and we do not write any of our own.
An HTML fragment is a piece of HTML that is not a whole document: a single <div> with a post card in it, or one comment. In the JSON style the server returns data and the browser builds the markup; in the HTMX style the server returns the fragment, already built.
These are the four attributes we use:
hx-postnames the URL to send aPOSTto when the element is triggered. On a<form>, the trigger is submission, and the form fields become the request body exactly as for a normal form.hx-targetis a CSS selector for the element the response goes into. Without it, HTMX swaps the response into the element that made the request.hx-swapsays where the response goes relative to the target:afterbegininserts it as the first child,beforeendas the last child,innerHTML(the default) replaces the target's contents,outerHTMLreplaces the target itself.hx-on::after-requestruns a small piece of inline code after the request finishes, on the element that carries it. We use it to clear a form.
Flask's url_for() builds a URL from the name of a view function (its endpoint) and the values for any variable parts of the route, so the code never hard-codes a path.
Practical Scenario
A small team at a startup wants a shared activity wall: a place to post updates, ask questions and leave comments that everyone sees. It has to feel live. When someone posts, the new card should appear at the top of the feed at once, and the half-written comment under another post should not be wiped out by a page reload. The team has one Flask developer and no frontend specialist.
The first version reloads the whole page on every submission. Each post redirects back to GET /, which renders the entire feed again; every comment does the same. With twenty people posting through the day, the scroll position jumps back to the top after every action and the full feed is sent over the wire each time. Rewriting it as a JavaScript client with a JSON API would take a week and would double the code that renders a post.
HTMX gives the team the live behaviour while keeping all rendering in Python: each form gets a few attributes, and each route returns one card or one comment instead of a redirect.
The Problem
Let's start with the plain version: one page that renders every post, and one route that stores a post and redirects back to the page. Watch what the browser has to do after each submission.
Create the file in /home/coder/learning:
touch social_wall.py
Put this code in it:
from flask import Flask, request, redirect, url_for
import time
import uuid
app = Flask(__name__)
POSTS = {}
@app.route("/")
def index():
sorted_posts = sorted(POSTS.items(), key=lambda item: item[1]['timestamp'], reverse=True)
posts_html = ""
for post_id, post in sorted_posts:
posts_html += f"<div><p>{post['author_name']}: {post['content']}</p></div>"
return f"<html><body><form method='POST' action='/posts/create'><textarea name='content'></textarea><button>Post</button></form>{posts_html}</body></html>"
@app.route("/posts/create", methods=["POST"])
def create_post():
content = request.form.get("content")
if content:
post_id = str(uuid.uuid4())
POSTS[post_id] = {
"author_name": "User",
"content": content,
"timestamp": int(time.time()),
"comments": []
}
return redirect(url_for("index"))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=9000, debug=True)
Run it:
python3 social_wall.py
* Serving Flask app 'social_wall'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:9000
* Running on http://172.17.0.3:9000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
The last line is followed by a Debugger PIN line whose value differs on every machine, and the 172.17.0.3 address is the sandbox's internal address, which will also differ for you.
Look at the last line of the file first: app.run(host="0.0.0.0", port=9000, debug=True). Flask's default is host="127.0.0.1" and port=5000, which means "accept connections only from this machine, on port 5000". Your sandbox has a public URL of the form https://webserver-p9000-<id1>-<id2>.bytestark.com (the two ids were shown when the sandbox launched). That URL reaches your app from outside the sandbox's loopback interface, and only on port 9000. 0.0.0.0 means "listen on every interface", which is what the Running on all addresses line confirms, and 9000 is the port the URL is wired to. debug=True turns on two things you will rely on: the reloader (Restarting with stat), which restarts the server every time you save the file, and the in-browser debugger that shows a traceback instead of a bare error page.
Open your sandbox URL in the browser, type a post and submit it. Then, in a second terminal, do the same with curl so that you can see what actually travels between browser and server:
curl -s -i -X POST -d "content=Standup moved to 10:30" http://127.0.0.1:9000/posts/create | grep -E '^HTTP|^Location'
HTTP/1.1 302 FOUND
Location: /
The status line HTTP/1.1 302 FOUND says "the thing you want is elsewhere", and the Location: / header says where. That is the redirect(url_for("index")) at the end of create_post. The browser follows it with a fresh GET /, and index() rebuilds the whole page: every post, the form, the <html> and <body> around them. In the server log you will see each submission as a pair, POST /posts/create ... 302 followed by GET / ... 200.
That pair is the cost the scenario describes. The browser throws away the current page, including the scroll position and anything typed into other fields, and loads a new one, and the amount of HTML sent grows with every post on the wall. Notice also how index() builds its HTML: one f-string per post, glued together by hand, with no way to reuse that markup anywhere else.
Try it: Post this text from the second terminal, then fetch the page: curl -s -X POST -d "content=<b>Deploy freeze</b> starts Friday" -o /dev/null http://127.0.0.1:9000/posts/create && curl -s http://127.0.0.1:9000/. Before running it, predict what the last <div> will contain. It is <div><p>User: <b>Deploy freeze</b> starts Friday</p></div>: the f-string pasted the user's text into the page unchanged, so the browser renders it as bold text. Replace <b> with a <script> tag and it would run in every visitor's browser. We fix this in the next sections.
Storage and a mock user
The rebuilt wall needs two things before any page exists: somewhere to keep posts, and a way to know who is posting. Replace the entire content of social_wall.py with:
from flask import Flask, request, url_for
from markupsafe import escape
import time
import uuid
app = Flask(__name__)
POSTS = {}
USERS = {}
def get_current_user_id():
mock_id = request.headers.get('X-Mock-User-Id', 'guest_1234')
if mock_id not in USERS:
USERS[mock_id] = f"User-{uuid.uuid4().hex[:6].upper()}"
return mock_id, USERS[mock_id]
if __name__ == "__main__":
app.run(host="0.0.0.0", port=9000, debug=True)
Save the file. The reloader restarts the server by itself; if you had stopped it, start it again with python3 social_wall.py. Then request the home page from the second terminal:
curl -s -i http://127.0.0.1:9000/ | head -1
HTTP/1.1 404 NOT FOUND
The 404 is expected: this version has no routes at all, so nothing answers /. What it does have:
POSTS = {}andUSERS = {}are the in-memory "database". They are ordinary module-level dictionaries, so they live exactly as long as the Python process. Every time the reloader restarts the server, they start empty again.from markupsafe import escapeimports the function we will use to make user text safe inside HTML.markupsafeis the library Flask and Jinja use for escaping, so it is always available where Flask is.get_current_user_id()stands in for real authentication.request.headers.get('X-Mock-User-Id', 'guest_1234')reads a request header, and falls back to'guest_1234'when the header is absent, which is always the case for a browser. The first time an id is seen, it gets a random display name,"User-"plus six upper-case hex characters from a fresh UUID, and that name is remembered inUSERS.- The function returns both values as a tuple: the stable id to store with a post, and the display name to show on it. In a real application the id would come from a session cookie or a token; the rest of the code would not change.
request only has a value while Flask is handling a request, so get_current_user_id() can only be called from inside a view. That is why it is a function and not a variable computed at import time.
Try it: Change the fallback 'guest_1234' to 'guest_5678' and predict whether anything visible changes. Nothing does yet, and you can confirm that / still returns 404: the function is defined but nothing calls it. We will come back to this header when two users post.
Rendering a post and a comment as fragments
HTMX inserts whatever HTML the server returns, so the first thing to build is the code that produces one post card and one comment. Both the full page and the HTMX responses will use these functions, which is how a post looks the same whether it arrived with the page or was added a moment ago.
Add these two functions to social_wall.py, after get_current_user_id() and before the if __name__ == "__main__": block:
def render_comment(comment_data):
return f"""
<div class="card card-body bg-light p-3 rounded shadow-sm">
<p class="mb-1 text-muted small">
<span class="fw-semibold text-primary">{escape(comment_data['author_name'])}</span>
@ {time.strftime('%H:%M', time.localtime(comment_data['timestamp']))}
</p>
<p class="mb-0 text-dark">{escape(comment_data['content'])}</p>
</div>
"""
def render_post_card(post_id, post_data, create_comment_url):
comments_html = "".join(render_comment(c) for c in post_data['comments'])
return f"""
<div id="post-{post_id}" class="card shadow mb-4">
<div class="card-body p-4">
<p class="text-muted small mb-2">
Posted by <span class="fw-semibold text-primary">{escape(post_data['author_name'])}</span>
@ {time.strftime('%H:%M:%S', time.localtime(post_data['timestamp']))}
</p>
<div class="bg-light p-3 rounded mb-4 border">
<p class="card-text text-dark mb-0">{escape(post_data['content'])}</p>
</div>
<div id="comments-list-{post_id}" class="mt-4 pt-4 border-top vstack gap-3">
{comments_html}
</div>
<form hx-post="{create_comment_url}"
hx-target="#comments-list-{post_id}"
hx-swap="beforeend"
hx-on::after-request="this.reset()"
class="mt-4 d-flex">
<input type="text" name="comment_content" placeholder="Add a comment..." required
class="form-control me-2">
<button type="submit" class="btn btn-primary shadow-sm">Comment</button>
</form>
</div>
</div>
"""
There is still no route, but these functions do not need one. render_comment only reads the dictionary it is given, so we can call it straight from the terminal. Importing social_wall does not start the server, because app.run(...) sits under if __name__ == "__main__":, which is only true when the file is run as a script:
python3 -c "from social_wall import render_comment; print(render_comment({'author_name': 'User-3F9A2C', 'content': 'Can we make it <10:45>?', 'timestamp': 0}))"
<div class="card card-body bg-light p-3 rounded shadow-sm">
<p class="mb-1 text-muted small">
<span class="fw-semibold text-primary">User-3F9A2C</span>
@ 00:00
</p>
<p class="mb-0 text-dark">Can we make it <10:45>?</p>
</div>
That printed text is exactly what the comment route will send back later. Here is how each part got there:
time.strftime('%H:%M', time.localtime(comment_data['timestamp']))turns the stored Unix timestamp into hours and minutes. Timestamp0is midnight on 1 January 1970 in UTC, and the sandbox runs in UTC, hence00:00.escape(comment_data['content'])turned<10:45>into<10:45>.<and>are the HTML entities for<and>: the browser displays them as the characters but never treats them as the start of a tag. This is the fix for the bold-text injection from The Problem, applied to every piece of user text: author names and contents.- The class names (
card,bg-light,text-primary, …) are Bootstrap's; they only affect how the card looks.
render_post_card builds on render_comment. Its parts:
"".join(render_comment(c) for c in post_data['comments'])renders every existing comment and concatenates them, so a post that already has comments arrives with them in place.id="post-{post_id}"andid="comments-list-{post_id}"give every card and every comment list an id that contains the post's UUID. Several posts are on the page at once, and each comment form needs to point at its own list.- The comment form is where HTMX enters.
hx-post="{create_comment_url}"sends the form to the comment route of this post.hx-target="#comments-list-{post_id}"names this post's list as the place for the answer.hx-swap="beforeend"appends the answer as the last child of that list, so comments stay in the order they were written.hx-on::after-request="this.reset()"runs after the request; on this elementthisis the form, andreset()is the browser's built-in method that empties its fields. create_comment_urlis a parameter rather than something the function works out itself. The caller knows which route builds that URL, and the renderer stays a pure function of its inputs, which is why we could call it from the terminal above.
Try it: Remove the escape(...) around comment_data['content'], save, and run the same python3 -c command. Predict the last line before you look. It becomes <p class="mb-0 text-dark">Can we make it <10:45>?</p>, and a browser would read <10:45> as a broken tag and silently drop it from the text. Put escape back.
The full page and the index route
Now the page itself: the header, the form for new posts, and the list of existing posts. Add this function and route after render_post_card and before the if __name__ block:
def render_main_page(current_user_name, create_post_url):
sorted_posts = sorted(POSTS.items(), key=lambda item: item[1]['timestamp'], reverse=True)
posts_html = "".join(
render_post_card(post_id, post_data, url_for('create_comment', post_id=post_id))
for post_id, post_data in sorted_posts
)
return f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Social Wall (Flask+HTMX)</title>
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<script src="/static/js/htmx.min.js"></script>
<style>body {{ background-color: #f8f9fa; }}</style>
</head>
<body class="p-3">
<div class="container-md mt-4">
<header class="pb-3 mb-4 border-bottom border-4 border-primary">
<h1 class="display-6 fw-bold text-dark">The HTMX Wall</h1>
<p class="text-secondary small">
You are logged in as:
<span id="userIdDisplay" class="fw-bold text-primary">{escape(current_user_name)}</span>
</p>
</header>
<form hx-post="{create_post_url}"
hx-target="#posts-container"
hx-swap="afterbegin"
hx-on::after-request="this.reset()"
class="card shadow-lg p-4 mb-4 border border-primary-subtle">
<h2 class="h5 card-title mb-3 text-dark">What's on your mind?</h2>
<textarea name="content" placeholder="Write your post here..." required
class="form-control mb-3" rows="3"></textarea>
<button type="submit" class="btn btn-primary btn-lg shadow">Post to Wall</button>
</form>
<div id="posts-container" class="vstack gap-4">
{posts_html}
</div>
</div>
</body>
</html>
"""
@app.route("/")
def index():
user_id, user_name = get_current_user_id()
return render_main_page(user_name, url_for('create_post'))
Save the file and request the page:
curl -s -o /dev/null -w "GET / -> %{http_code}\n" http://127.0.0.1:9000/
GET / -> 500
A 500 means the view raised an exception. The server terminal shows the traceback; its last lines are:
File "/usr/local/lib/python3.12/site-packages/werkzeug/routing/map.py", line 901, in build
raise BuildError(endpoint, values, method, self)
werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'create_post'. Did you mean 'static' instead?
The error comes from url_for('create_post') in index(). url_for does not guess paths: it looks the endpoint name up in the table of registered routes, and that table only has an entry once a function decorated with @app.route exists. We have not written create_post yet, so the lookup fails, and Werkzeug, the library underneath Flask that does the routing, suggests the only endpoint it knows, static. This is the benefit of url_for over writing "/posts/create/" by hand: a URL that points at nothing fails loudly the first time the page renders, not silently when a user clicks.
The rest of the page code, read top to bottom:
sorted(POSTS.items(), key=lambda item: item[1]['timestamp'], reverse=True)orders posts newest first.itemis a(post_id, post)pair, soitem[1]['timestamp']is the post's time.- For each post,
url_for('create_comment', post_id=post_id)builds that post's comment URL, and the card is rendered with it. - In the f-string,
{{and}}produce literal{and}. The CSS rulebody {{ background-color: #f8f9fa; }}needs real braces, and a single{would start a placeholder. - The two
/static/...paths load Bootstrap's stylesheet and HTMX from the sandbox'sstatic/folder. Because the sandbox URL serves the app from the root path, they work there exactly as on127.0.0.1. - The post form uses the same three attributes as the comment form. Here
hx-target="#posts-container"withhx-swap="afterbegin"puts the new card first, matching the newest-first order of the initial render. hx-on::after-request="this.reset()"sits on the<form>itself. HTMX fires itsafter-requestevent on the element that sent the request, the form, so the handler has to be on the form. On an element inside the form it never runs: an event bubbles up from the form to its ancestors, never down to its children.index()gets the current user's display name and passes it, together with the URL of the post route, to the renderer.
Try it: Without adding any code, predict what GET / will return once create_post exists. Hold on to that prediction for the next section, which checks it.
Creating a post returns one card
This route is the heart of the HTMX approach: instead of storing the post and redirecting, it stores the post and returns its card. Add it after index():
@app.route("/posts/create/", methods=["POST"])
def create_post():
content = request.form.get("content")
if not content:
return "", 400
user_id, user_name = get_current_user_id()
post_id = str(uuid.uuid4())
new_post = {
"user_id": user_id,
"author_name": user_name,
"content": content,
"timestamp": int(time.time()),
"comments": []
}
POSTS[post_id] = new_post
create_comment_url = url_for('create_comment', post_id=post_id)
return render_post_card(post_id, new_post, create_comment_url)
Save, then load the page and create one post from the second terminal:
curl -s -o /dev/null -w "GET / -> %{http_code}\n" http://127.0.0.1:9000/
curl -s -o /dev/null -w "POST /posts/create/ -> %{http_code}\n" -X POST -d "content=Standup moved to 10:30 tomorrow" http://127.0.0.1:9000/posts/create/
curl -s -o /dev/null -w "GET / -> %{http_code}\n" http://127.0.0.1:9000/
GET / -> 200
POST /posts/create/ -> 500
GET / -> 500
If you predicted a 500 for the first request, here is why it is 200. index() now finds create_post, and the only other url_for call, the one for comments, sits inside the loop over posts. There are no posts yet, so that loop runs zero times and the missing endpoint is never looked up. The POST then fails at url_for('create_comment', post_id=post_id) at the end of create_post, with the same kind of error as before:
werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'create_comment' with values ['post_id']. Did you mean 'create_post' instead?
But the post was already stored in POSTS before that line ran, so the page is now broken too: the loop has a post to render and hits the same lookup. A bug that only appears once there is data is a common shape of failure, and it is exactly what these three requests show.
The route itself, line by line:
@app.route("/posts/create/", methods=["POST"])registers the endpointcreate_postforPOSTonly. AGETto this URL gets405 Method Not Allowed.request.form.get("content")reads the field namedcontentfrom the form-encoded body. HTMX sends a form's fields in exactly the format a normal submission uses, so Flask cannot tell the two apart.return "", 400answers an empty post with an empty body and status400 Bad Request. By default HTMX does not swap the response of a4xxor5xxrequest, so nothing is inserted into the page.post_id = str(uuid.uuid4())gives the post a random, unique id that is safe to use in URLs and in HTML ids.return render_post_card(...)is the key difference from The Problem. The response is the card's HTML and nothing else, with status200. HTMX takes it and inserts it at the start of#posts-container.
Try it: Comment out the return "", 400 line together with the if above it, save, and post an empty content= with curl. Predict the status code. It is 200, and the response is a card with an empty body: without the check, the browser would show a blank post at the top of the wall. Restore the two lines.
Adding comments
The last missing endpoint is the comment route. Add it after create_post:
@app.route("/posts/<post_id>/comments/create/", methods=["POST"])
def create_comment(post_id):
comment_content = request.form.get("comment_content")
if not comment_content or post_id not in POSTS:
return "", 400
user_id, user_name = get_current_user_id()
new_comment = {
"user_id": user_id,
"author_name": user_name,
"content": comment_content,
"timestamp": int(time.time())
}
POSTS[post_id]['comments'].append(new_comment)
return render_comment(new_comment)
Save the file. The reloader restarts the server, and that empties POSTS, so the broken post from the previous section is gone and GET / is back to 200. Create a post and look at the full response:
curl -s -X POST -d "content=Standup moved to 10:30 tomorrow" http://127.0.0.1:9000/posts/create/
<div id="post-9fc9233c-c66f-41ce-b1de-31259725df9e" class="card shadow mb-4">
<div class="card-body p-4">
<p class="text-muted small mb-2">
Posted by <span class="fw-semibold text-primary">User-5F25E7</span>
@ 08:13:30
</p>
<div class="bg-light p-3 rounded mb-4 border">
<p class="card-text text-dark mb-0">Standup moved to 10:30 tomorrow</p>
</div>
<div id="comments-list-9fc9233c-c66f-41ce-b1de-31259725df9e" class="mt-4 pt-4 border-top vstack gap-3">
</div>
<form hx-post="/posts/9fc9233c-c66f-41ce-b1de-31259725df9e/comments/create/"
hx-target="#comments-list-9fc9233c-c66f-41ce-b1de-31259725df9e"
hx-swap="beforeend"
hx-on::after-request="this.reset()"
class="mt-4 d-flex">
<input type="text" name="comment_content" placeholder="Add a comment..." required
class="form-control me-2">
<button type="submit" class="btn btn-primary shadow-sm">Comment</button>
</form>
</div>
</div>
Your UUID, user name and time will differ. The UUID and the name are random, and the time is when you ran the command. Notice that the same UUID appears four times. It is the card's id, the comment list's id, the path segment of the comment URL that url_for built, and the selector in hx-target. That is what ties the comment form to its own list. Copy your UUID and post a comment to it, replacing <post_id>:
curl -s -X POST -d "comment_content=Can we make it 10:45?" http://127.0.0.1:9000/posts/<post_id>/comments/create/
<div class="card card-body bg-light p-3 rounded shadow-sm">
<p class="mb-1 text-muted small">
<span class="fw-semibold text-primary">User-5F25E7</span>
@ 08:13
</p>
<p class="mb-0 text-dark">Can we make it 10:45?</p>
</div>
How the route produces that:
"/posts/<post_id>/comments/create/"has a variable part: whatever stands in that segment of the URL is passed to the function as thepost_idargument. That is also whyurl_for('create_comment', post_id=...)needed a value forpost_id: it fills the same slot in the other direction.if not comment_content or post_id not in POSTSrejects an empty comment and a comment on a post that does not exist, with400. Try/posts/no-such-post/comments/create/and you get400, not a crash with aKeyError.POSTS[post_id]['comments'].append(new_comment)stores the comment inside its post, which is howrender_post_cardfinds it on the next full page load.return render_comment(new_comment)sends back only the new comment. HTMX appends it to the end of#comments-list-<post_id>.
Now open your sandbox URL in the browser (https://webserver-p9000-<id1>-<id2>.bytestark.com/). The post and comment you created with curl are there, because they live in the server's POSTS, not in any one client. Write a post in the form and submit it. The card appears at the top of the wall, the textarea empties, and the page does not reload: the address bar does not change and the scroll position stays where it was. Add a comment under any post and it appears at the bottom of that post's list. In the server terminal, each action is now a single line, POST /posts/create/ ... 200 or POST /posts/<id>/comments/create/ ... 200, with no GET / after it.
Try it: Post as a second user by sending the header the mock login reads: curl -s -X POST -H "X-Mock-User-Id: ops_lead" -d "content=Release notes are in the shared folder" http://127.0.0.1:9000/posts/create/ | grep 'Posted by'. Predict whether the name matches yours. It does not: ops_lead is a new id, so get_current_user_id() invents a new User-XXXXXX name for it, and that name stays the same on every later request with that header. Reload the browser and the new card is at the top, rendered by index() this time instead of by HTMX, with the same markup.
Note: Every save of social_wall.py restarts the server, and the restart empties POSTS and USERS. If the wall is suddenly empty and your name has changed, that is the reloader, not a bug.
The complete application
Here is the whole of social_wall.py, for reference and to check your copy against. Nothing in it is new: it is the five pieces from the previous sections in order.
from flask import Flask, request, url_for
from markupsafe import escape
import time
import uuid
app = Flask(__name__)
POSTS = {}
USERS = {}
def get_current_user_id():
mock_id = request.headers.get('X-Mock-User-Id', 'guest_1234')
if mock_id not in USERS:
USERS[mock_id] = f"User-{uuid.uuid4().hex[:6].upper()}"
return mock_id, USERS[mock_id]
def render_comment(comment_data):
return f"""
<div class="card card-body bg-light p-3 rounded shadow-sm">
<p class="mb-1 text-muted small">
<span class="fw-semibold text-primary">{escape(comment_data['author_name'])}</span>
@ {time.strftime('%H:%M', time.localtime(comment_data['timestamp']))}
</p>
<p class="mb-0 text-dark">{escape(comment_data['content'])}</p>
</div>
"""
def render_post_card(post_id, post_data, create_comment_url):
comments_html = "".join(render_comment(c) for c in post_data['comments'])
return f"""
<div id="post-{post_id}" class="card shadow mb-4">
<div class="card-body p-4">
<p class="text-muted small mb-2">
Posted by <span class="fw-semibold text-primary">{escape(post_data['author_name'])}</span>
@ {time.strftime('%H:%M:%S', time.localtime(post_data['timestamp']))}
</p>
<div class="bg-light p-3 rounded mb-4 border">
<p class="card-text text-dark mb-0">{escape(post_data['content'])}</p>
</div>
<div id="comments-list-{post_id}" class="mt-4 pt-4 border-top vstack gap-3">
{comments_html}
</div>
<form hx-post="{create_comment_url}"
hx-target="#comments-list-{post_id}"
hx-swap="beforeend"
hx-on::after-request="this.reset()"
class="mt-4 d-flex">
<input type="text" name="comment_content" placeholder="Add a comment..." required
class="form-control me-2">
<button type="submit" class="btn btn-primary shadow-sm">Comment</button>
</form>
</div>
</div>
"""
def render_main_page(current_user_name, create_post_url):
sorted_posts = sorted(POSTS.items(), key=lambda item: item[1]['timestamp'], reverse=True)
posts_html = "".join(
render_post_card(post_id, post_data, url_for('create_comment', post_id=post_id))
for post_id, post_data in sorted_posts
)
return f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Social Wall (Flask+HTMX)</title>
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<script src="/static/js/htmx.min.js"></script>
<style>body {{ background-color: #f8f9fa; }}</style>
</head>
<body class="p-3">
<div class="container-md mt-4">
<header class="pb-3 mb-4 border-bottom border-4 border-primary">
<h1 class="display-6 fw-bold text-dark">The HTMX Wall</h1>
<p class="text-secondary small">
You are logged in as:
<span id="userIdDisplay" class="fw-bold text-primary">{escape(current_user_name)}</span>
</p>
</header>
<form hx-post="{create_post_url}"
hx-target="#posts-container"
hx-swap="afterbegin"
hx-on::after-request="this.reset()"
class="card shadow-lg p-4 mb-4 border border-primary-subtle">
<h2 class="h5 card-title mb-3 text-dark">What's on your mind?</h2>
<textarea name="content" placeholder="Write your post here..." required
class="form-control mb-3" rows="3"></textarea>
<button type="submit" class="btn btn-primary btn-lg shadow">Post to Wall</button>
</form>
<div id="posts-container" class="vstack gap-4">
{posts_html}
</div>
</div>
</body>
</html>
"""
@app.route("/")
def index():
user_id, user_name = get_current_user_id()
return render_main_page(user_name, url_for('create_post'))
@app.route("/posts/create/", methods=["POST"])
def create_post():
content = request.form.get("content")
if not content:
return "", 400
user_id, user_name = get_current_user_id()
post_id = str(uuid.uuid4())
new_post = {
"user_id": user_id,
"author_name": user_name,
"content": content,
"timestamp": int(time.time()),
"comments": []
}
POSTS[post_id] = new_post
create_comment_url = url_for('create_comment', post_id=post_id)
return render_post_card(post_id, new_post, create_comment_url)
@app.route("/posts/<post_id>/comments/create/", methods=["POST"])
def create_comment(post_id):
comment_content = request.form.get("comment_content")
if not comment_content or post_id not in POSTS:
return "", 400
user_id, user_name = get_current_user_id()
new_comment = {
"user_id": user_id,
"author_name": user_name,
"content": comment_content,
"timestamp": int(time.time())
}
POSTS[post_id]['comments'].append(new_comment)
return render_comment(new_comment)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=9000, debug=True)
python3 social_wall.py
* Serving Flask app 'social_wall'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:9000
* Running on http://172.17.0.3:9000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
Compare it with The Problem on the same action, posting one message. There, the browser sent a POST, received 302 Found, sent a GET /, and received and redrew the whole document. Here, HTMX sends the same POST with the same form body, receives one <div>, and inserts it into #posts-container; nothing else on the page is touched. The render functions are shared between the two paths, the full page and the fragment, so there is one definition of what a post looks like. The page has no JavaScript of our own: the hx-* attributes are the only client-side code.
The tutorial deliberately leaves out persistence, real authentication and CSRF protection. A real wall would store posts in a database, identify users from a session, and protect the POST routes with a CSRF token, which HTMX can send in a header.
Try it: Delete hx-target="#posts-container" from the post form, save, reload the browser and submit a post. Predict where the card goes. Without hx-target, HTMX swaps the response into the element that made the request, the form itself, and afterbegin puts the card inside the form, above "What's on your mind?". Put the attribute back.
Summary
We rebuilt a full-reload Flask wall into one where posts and comments appear instantly. The server returns HTML fragments, and HTMX inserts them where hx-target and hx-swap say. Storage is an in-memory dictionary and the login is a mocked header; persistence, real authentication and CSRF tokens are out of scope.
- A server bound to
127.0.0.1is unreachable from the sandbox URL;app.run(host="0.0.0.0", port=9000)listens on every interface on the port the URL is wired to. - A redirect after
POSTmakes the browser reload the whole page; returning a fragment with status200lets HTMX update one element and leave the rest of the page alone. hx-postsends the form's fields exactly as a normal submission would, so the Flask route reads them withrequest.formeither way.hx-targetpicks the element that receives the response; without it, the response goes into the element that made the request.hx-swap="afterbegin"inserts as the first child (newest-first feeds),beforeendas the last (comments in order).- HTMX does not swap
4xxor5xxresponses by default, so returning400for invalid input keeps broken fragments out of the page. hx-on::after-requestmust sit on the element that sends the request, because the event fires there and bubbles up, never down.- One render function per component, used for both the full page and the fragment, keeps a post looking the same however it reached the page.
- Every piece of user text goes through
escape()before it is placed in HTML, so<b>or<script>typed by a user is shown as text and never interpreted. url_forbuilds URLs from endpoint names and fails withBuildErrorwhen the endpoint does not exist, which surfaces a broken link the first time the code runs.