我正在为运行 FastAPI 的 API 服务制定一个客户端的概念。我需要 Fast API 来通过不同的端点提供 API 和 HTML。
我的FastAPI代码:
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/api/v1", response_class=JSONResponse)
async def api_home():
data = {"key": "value"}
return data
在此代码中,我的客户端 ping API 端点并获取 json 响应:
<div class="container">
<h1 class="h2">API Client</h1>
<a hx-get="/api/v1" hx-target="#content" hx-swap="innerHTML" class="btn btn-primary">Fetch data</a>
<div id="content">{{ key | default("No message received") }}</div>
</div>
但结果是:
{"key": "value"}
我只需要在模板中渲染
value
。怎么办?
由于您使用 hx-get 来获取数据,因此假设您使用 HTMX 来获取数据。您可以通过向按钮添加 hx-trigger 属性来在获取数据时调用 JavaScript 函数来实现此目的。喜欢:
`
<a hx-get="/api/v1" hx-trigger="fetchCompleted(xhr, 'content')" ...
...
// At the bottom of your code you may add JS code in order to update contents.
<script>
function fetchCompleted(xhr, targetId) {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
var content = data.key || "No message received";
document.getElementById(targetId).innerText = content;
}
}
</script>
`