源代碼: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支持該項目。
![]()