-
This is an interesting problem. I want to make a solution for this on htmx [1]-patterns. I would make user specific routes with an hx-get rather than serving the whole page, serve a partial with hx-oobs to fill in user specific data with a no cache on the cdn level.
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: /htmx/
[2]: /thoughts/
Posts tagged: dev
All posts with the tag "dev"
291 posts
latest post 2026-05-09
Publishing rhythm
-
So cool to see ROX build this over the course of a day.
Note
This post is a thought [1]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: /thoughts/
jinja has a loop variable that is very handy to use with htmx [1]. Whether you
want to implement a click to load more or an infinite scroll this loop variable
is very handy.
{% for person in persons %}
<li
{% if loop.last %}
hx-get="{{ url_for('infinite', page=next_page) }}"
hx-trigger="intersect once"
hx-target="#persons"
hx-swap='beforeend'
hx-indicator="#persons-loading"
{% endif %}
{{ person.name.upper() }} -
{{ person.phone_number }}
</li>
{% endfor %}
Now for every chunk of contacts that we load we will trigger the infinite
scroll by loading more once the last one has intersected the screen.
References:
[1]: /htmx/
-
Great episode covering a seemingly simple topic. What I really benefitted from was hearing all the different use cases, from logging, debugging, to a/b testing, caching, and auth. I hadn’t even thought of it being applied to a router. I thought of it being applied for an entire application. This seems very useful for things like an admin router, all routes would need to have the admin role to get in.
Note
This post is a thought [1]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: /thoughts/
![[None]]
I’ve been using these decorators to modify the behavior of specific routes. It will do things like 404 admin only routes in a way that looks just like fastapi [1]’s default, or only allow certain roles into the route, or redirect unauthenticated users to login.
After listening to yesterday’s syntaxfm I’m now really thinking about middleware and the benefits it might have. middleware would make it easy to apply things like admin to an entire admin router, so you wont forget it on any one admin route. It will look cleaner as the admin checker is only applied once per router, not once per route.
import inspect
import time
from functools import wraps
from inspect import signature
from fastapi import Request
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from starlette import status
from fokais.config import get_config
from fokais.models.user import Role
config = get_config()
admin_routes = []
authenticated_routes = []
not_cached_routes = []
cached_routes = []
def not_found(request):
hx_request_header = request.headers.get("hx-request")
user_agent = request.headers.get("user-agent", "").lower()
if "mozilla" in user_agent or "webkit" i...
External Link
X (formerly Twitter) · twitter.com [1]
Huh, so this is just built right into the chrome cli.
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
--headless \
--screenshot=/tmp/shot1.png \
https://simonwillison.net
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://twitter.com/simonw/status/1772043579231445366
[2]: /thoughts/
![[None]]
jinja’s url_for in fastapi [1] does not account for https by default, there is
probably a better way, but this is a way that allows me to configure when I use
http vs https.
@pass_context
def https_url_for(context: dict, name: str, **path_params: Any) -> str:
"""
always convert http to https
"""
request = context["request"]
http_url = request.url_for(name, **path_params)
return str(http_url).replace("http", "https", 1)
def get_templates(config: BaseSettings) -> Jinja2Templates:
templates = Jinja2Templates(directory="templates")
templates.env.globals["https_url_for"] = https_url_for
## only use the default url_for for local development, for dev, qa, and prod use https
if os.environ.get("ENV") in ["dev", "qa", "prod"]:
templates.env.globals["url_for"] = https_url_for
console.print("Using HTTPS")
else:
console.print("Using HTTP")
return templates
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: /fastapi/
[2]: /thoughts/
![[None]]
import logging
from typing import List
import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
logger = logging.getLogger(__name__)
authors = {}
books = {}
book_authors = {}
authors_books = {}
def get_author_for_book(root) -> "Author":
return authors[book_authors[root.id]]
@strawberry.type
class Book:
id: int
title: str
author: "Author" = strawberry.field(resolver=get_author_for_book)
def get_books_for_author(root) -> List[Book]:
print(f"getting books for {root}")
return [books[i] for i in authors_books[root.id]]
@strawberry.type
class Author:
id: int
name: str
books: List[Book] = strawberry.field(resolver=get_books_for_author)
authors = {1: Author(id=1, name="Michael Crichton")}
books = {1: Book(id=1, title="Jurassic Park")}
# relationships
book_authors[1] = 1
authors_books[1] = [1]
def get_author_by_id(id: int) -> Author:
return authors.get(id)
def get_book_by_id(id: int) -> Book:
return books.get(id)
def get_authors(root) -> List[Author]:
return authors.values()
def get_books(root) -> List[Book]:
print(books)
print(authors)
print(book_authors)
print(authors_books)
return books.values()
@strawberry.typ...
605: Jim Nielsen on Subversive URLs, Blogging + AI, and Design Engineers
Jim Nielsen joins us to about URLs and linking as the new subversive way to maintain the web, paying for news in Canada, should content creators be worried about AI, the case for design engineers, …
ShopTalk · shoptalkshow.com [1]
An absolute fantastic episode about blogging, thinking about a web1.0 kind of world today, and what it means moving forward.
Web 1.0 is robust, you own your own destiny, you own your data, you can do what you want. There is no platform to tell you what you can and cannot do. But the future web is stealing your data to build AI models, spam sites are duplicating your content and stealing your SEO. You may or may not care, but at the end whether you get traffic or now you own your web 1.0 sites.
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://shoptalkshow.com/605/
[2]: /thoughts/
Placehold
Placehold is a simple, fast and free image placeholder service to generate SVG, PNG, JPEG, GIF, WebP and AVIF placeholder images for your project.
placehold.co [1]
This is a handy placeholder generator for generating placeholder items like images, and videos.
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://placehold.co/
[2]: /thoughts/
tailwind and markdown
This post is a bit of an experiment to see what I can do. Lets start with a
block of pink text. I build my blog with my own static site generator called markata [1]
Setup Tailwind for Jinja [2]
Still Loving Tailwind [3]
{.text-pink-500}
This text should be pink
This text should be not pink
---
This text should be pink
This text should be not pink
---
Now will it work with bulleted lists
{.text-pink-500}
This block will be pink
{.text-pink-500}
* Lorem ipsum dolor sit amet, officia excepteur ex fugiat reprehenderit enim
* labore culpa sint ad nisi Lorem pariatur mollit ex esse exercitation amet. Nisi
* anim cupidatat excepteur officia. Reprehenderit nostrud nostrud ipsum Lorem est
This block will not be pink.
* Lorem ipsum dolor sit amet, officia excepteur ex fugiat reprehenderit enim
* labore culpa sint ad nisi Lorem pariatur mollit ex esse exercitation amet. Nisi
* anim cupidatat excepteur officia. Reprehenderit nostrud nostrud ipsum Lorem est
---
- Lorem ipsum dol...
-
Great take on low code. I have definitely felt the pressure of being presented low code options, “look it does almost everything you need, and you can do it without code.” Granted there are tons of great low code environments that serve their markets well (things like zapier).
As pointed out here when they fall short rather than being hard, it goes to nearly impossible. As Theo points out here many applications follow an 80/20 rule. 80% of the app is really easy to put together, and takes about 20% of the time, probably less. What no code does is it takes that 80% that is already easy, makes it even easier ( pitches it as faster whether or not that is true ), and makes the last 20% of the project impossibly hard to create and maintain, so you just should have picked a tool that had the capability of doing the whole thing from the start anyways.
Note
This post is a thought [1]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: /thoughts/
Template Designer Documentation — Jinja Documentation (3.1.x)
jinja.palletsprojects.com [1]
html [2] code generated by my jinja templates generally look half garbage because of indents and whitespace all over the place. I just learned about these pesky Whitespace Control characters that can get rid of the whitespace added from templating.
You can also strip whitespace in templates by hand. If you add a minus sign (-) to the start or end of a block (e.g. a For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed:
{% for item in seq -%}
{{ item }}
{%- endfor %}
Note
This post is a thought [3]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://jinja.palletsprojects.com/en/3.0.x/templates/#whitespace-control
[2]: /html/
[3]: /thoughts/
bunny.net - The Global Edge Platform that truly Hops
Hop on bunny.net and speed up your web presence with the next-generation Content Delivery Service (CDN), Edge Storage, and Optimization Services at any scale.
bunny.net · bunny.net [1]
bunny.net looks like an interesting cloudflare alternative.
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://bunny.net/
[2]: /thoughts/
External Link
stackoverflow.com [1]
After struggling to get dependencies inside of middleware I learned that you can make global dependencies at the app level. I used this to set the user on every single route of the application without needing Depend on getting the user on each route.
from fastapi import Depends, FastAPI, Request
def get_db_session():
print("Calling 'get_db_session(...)'")
return "Some Value"
def get_current_user(session=Depends(get_db_session)):
print("Calling 'get_current_user(...)'")
return session
def recalculate_resources(request: Request, current_user=Depends(get_current_user)):
print("calling 'recalculate_resources(...)'")
request.state.foo = current_user
app = FastAPI(dependencies=[Depends(recalculate_resources)])
@app.get("/")
async def root(request: Request):
return {"foo_from_dependency": request.state.foo}
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://stackoverflow.com/questions/72243379/fastapi-dependency-inside-middleware#answer-72480781
[2]: /thoughts/
Handling Errors - FastAPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
fastapi.tiangolo.com [1]
This page shows how to customize your fastapi [2] errors. I found this very useful to setup common templates so that I can return the same 404’s both programatically and by default, so it all looks the same to the end user.
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
app = FastAPI()
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
)
@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
if name == "yolo":
raise UnicornException(name=name)
return {"unicorn_name": name}
Note
This post is a thought [3]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://fastapi.tiangolo.com/tutorial/handling-errors/
[2]: /fastapi/
[3]: /thoughts/
External Link
github.com [1]
Setting an additional log handler to the uvicorn logger for access logs in fastapi [2] was not straightforward, but This post was very helpful.
@app.on_event("startup")
async def startup_event():
logger = logging.getLogger("uvicorn.access")
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(handler)
Note
This post is a thought [3]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://github.com/tiangolo/fastapi/issues/1508
[2]: /fastapi/
[3]: /thoughts/
External Link
stackoverflow.com [1]
Setting tags in your fastapi endpoints will group them in the docs. You can also set some metadata around the tags to get nice descriptions.
Here is a full example from the post.
from fastapi import FastAPI
tags_metadata = [
{"name": "Get Methods", "description": "One other way around"},
{"name": "Post Methods", "description": "Keep doing this"},
{"name": "Delete Methods", "description": "KILL 'EM ALL"},
{"name": "Put Methods", "description": "Boring"},
]
app = FastAPI(openapi_tags=tags_metadata)
@app.delete("/items", tags=["Delete Methods"])
@app.put("/items", tags=["Put Methods"])
@app.post("/items", tags=["Post Methods"])
@app.get("/items", tags=["Get Methods"])
async def handle_items():
return
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://stackoverflow.com/questions/63762387/how-to-group-fastapi-endpoints-in-swagger-ui#answer-63762765
[2]: /thoughts/
Show some equivalent list comprehensions in filter examples · Issue #1068 · pallets/jinja
I'm willing to write a pull-request for this, but I just want to see what people think before I write it. So the issue is this. I'm very familiar with python. I'm new to Jinja2. Often I find myself...
GitHub · github.com [1]
I often want to reach for non existing list comprehensions in jinja 2, Here are a few nice equivalents.
a: {{ data | selectattr('x', 'gt', 5) | list }}
b: {{ data | map(attribute='c') | list }}
c: {{ data | selectattr('x', 'gt', 5) | map(attribute='c') | list }}
Note
This post is a thought [2]. It’s a short note that I make
about someone else’s content online #thoughts
References:
[1]: https://github.com/pallets/jinja/issues/1068
[2]: /thoughts/
I am working on fokais.com’s signup page, and I want to hide the form input during
an htmx [1] request. I was seeing some issues where I was able to prevent spamming
the submit button, but was still able to get one extra hit on it.
It also felt like nothing was happening while sending the email to the user for
verification. Now I get the form to disappear and a spinner to show during the
request.
HTML # [3]
Let’s start off with the form. It uses htmx to submit a post request to the
post_request route. Note that there is a spinner in the post_request with the
htmx-indicator class.
The intent is to hide the spinner until the request is running, and hide all of
the form input during the request.
<form
id="signup-form"
hx-swap-oob="outerHTML"
class="m-4 mx-auto mb-6 flex w-80 flex-col rounded-lg b p-4 shadow-xlc shadow-cyan-500/10"
method="POST"
action="{{ url_for('post_signup') }}"
hx-post="{{ url_for('post_signup') }}"
>
<input
class="mx-8 mt-6 mb-4 border border-black bg-zinc-900 p-1 text-center focus:bg-zinc-800"
type="text"
value="{{ full_name }}"
name="full_name"
placeholder="Full Name"
/>
{% if full_name_error %}
<label class="-mt-6 mb-6 mx-8 text-red-500 ...