源代码:https://github.com/volfpeter/fasthx
文档和示例:https://volfpeter.github.io/fasthx
FastAPI服务器端渲染具有内置的HTMX支持。
关键功能:
htmy , jinja2或dominate 。该包在PYPI上可用,可以安装:
$ pip install fasthx该软件包具有以下官方集成的可选依赖性:
pip install fasthx[htmy] 。pip install fasthx[jinja] 。 有关完整但简单的示例,显示了FastHX的基本用途,请参阅示例文件夹。
要求: pip install fasthx[htmy] 。
使用HTMY服务HTML和HTMX请求就像创建fasthx.htmy.HTMY实例以及在路由上使用hx()和page()装饰方法一样容易。
下面的示例假定存在不IndexPage UserList htmy组件。与htmy组件的完整示例可以在此处找到。
from datetime import date
from fastapi import FastAPI
from pydantic import BaseModel
from fasthx . htmy import HTMY
# Pydantic model for the application
class User ( BaseModel ):
name : str
birthday : date
# Create the FastAPI application.
app = FastAPI ()
# Create the FastHX HTMY instance that renders all route results.
htmy = HTMY ()
@ app . get ( "/users" )
@ htmy . hx ( UserList ) # Render the result using the UserList component.
def get_users ( rerenders : int = 0 ) -> list [ User ]:
return [
User ( name = "John" , birthday = date ( 1940 , 10 , 9 )),
User ( name = "Paul" , birthday = date ( 1942 , 6 , 18 )),
User ( name = "George" , birthday = date ( 1943 , 2 , 25 )),
User ( name = "Ringo" , birthday = date ( 1940 , 7 , 7 )),
]
@ app . get ( "/" )
@ htmy . page ( IndexPage ) # Render the index page.
def index () -> None : ...要求: pip install fasthx[jinja] 。
要开始服务HTML和HTMX请求,您需要做的就是创建一个fasthx.Jinja的实例,然后将其hx()或page()方法用作路由上的装饰器。 hx()仅触发HTML渲染HTMX请求,而page()无条件地呈现HTML。请参阅下面的示例代码:
from fastapi import FastAPI
from fastapi . templating import Jinja2Templates
from fasthx import Jinja
from pydantic import BaseModel
# Pydantic model of the data the example API is using.
class User ( BaseModel ):
first_name : str
last_name : str
# Create the app.
app = FastAPI ()
# Create a FastAPI Jinja2Templates instance and use it to create a
# FastHX Jinja instance that will serve as your decorator.
jinja = Jinja ( Jinja2Templates ( "templates" ))
@ app . get ( "/" )
@ jinja . page ( "index.html" )
def index () -> None :
...
@ app . get ( "/user-list" )
@ jinja . hx ( "user-list.html" )
async def htmx_or_data () -> list [ User ]:
return [
User ( first_name = "John" , last_name = "Lennon" ),
User ( first_name = "Paul" , last_name = "McCartney" ),
User ( first_name = "George" , last_name = "Harrison" ),
User ( first_name = "Ringo" , last_name = "Starr" ),
]
@ app . get ( "/admin-list" )
@ jinja . hx ( "user-list.html" , no_data = True )
def htmx_only () -> list [ User ]:
return [ User ( first_name = "Billy" , last_name = "Shears" )]请参阅此处的完整工作示例。
要求: pip install fasthx 。
如果您想在没有FASTHX集成的情况下使用渲染引擎,则可以轻松地在hx()和page()装饰器上构建,从而为您提供所需的所有功能。您需要做的就是实现HTMLRenderer协议。
与Jinja情况类似, hx()仅触发HTML请求的HTML渲染,而page()无条件地呈现HTML。请参阅下面的示例代码:
from typing import Annotated , Any
from fastapi import Depends , FastAPI , Request
from fasthx import hx , page
# Create the app.
app = FastAPI ()
# Create a dependecy to see that its return value is available in the render function.
def get_random_number () -> int :
return 4 # Chosen by fair dice roll.
DependsRandomNumber = Annotated [ int , Depends ( get_random_number )]
# Create the render methods: they must always have these three arguments.
# If you're using static type checkers, the type hint of `result` must match
# the return type annotation of the route on which this render method is used.
def render_index ( result : list [ dict [ str , str ]], * , context : dict [ str , Any ], request : Request ) -> str :
return "<h1>Hello FastHX</h1>"
def render_user_list ( result : list [ dict [ str , str ]], * , context : dict [ str , Any ], request : Request ) -> str :
# The value of the `DependsRandomNumber` dependency is accessible with the same name as in the route.
random_number = context [ "random_number" ]
lucky_number = f"<h1> { random_number } </h1>"
users = "" . join (( "<ul>" , * ( f"<li> { u [ 'name' ] } </li>" for u in result ), "</ul>" ))
return f" { lucky_number } n { users } "
@ app . get ( "/" )
@ page ( render_index )
def index () -> None :
...
@ app . get ( "/htmx-or-data" )
@ hx ( render_user_list )
def htmx_or_data ( random_number : DependsRandomNumber ) -> list [ dict [ str , str ]]:
return [{ "name" : "Joe" }]
@ app . get ( "/htmx-only" )
@ hx ( render_user_list , no_data = True )
async def htmx_only ( random_number : DependsRandomNumber ) -> list [ dict [ str , str ]]:
return [{ "name" : "Joe" }]请参阅此处的完整工作示例。
Jinja2示例,其功能,诸如主动搜索,懒惰,服务器式事件,自定义服务器端HTMX触发器,对话框以及TailWindCSS和Daisyui集成等功能。 此软件包的唯一依赖性是fastapi 。
使用ruff进行覆盖和格式,用于静态代码分析的mypy ,以及用于测试的pytest 。
该文档是使用mkdocs-material和mkdocstrings构建的。
随时提出问题或请求新功能。
当然,欢迎所有贡献,包括更多文档,示例,代码和测试。
目的是使fasthx成为一个全面的项目,即使您最复杂的HTMX用例也易于实现。
该包在MIT许可证的条件下开源。
感谢Smart-now支持该项目。
![]()