You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中使用Jinja2遍历字典遇内部服务器错误的解决方法

解决FastAPI返回字典时Jinja2模板渲染的Internal Server Error问题

我用FastAPI实现了两个GET接口,分别返回字符串和字典,通过Jinja2Templates渲染前端模板。需求是返回字符串时直接展示,返回字典时遍历打印键值对,但调用返回字典的/dic接口时出现Internal Server Error,相关代码如下:

后端代码

from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request
import uvicorn

app = FastAPI()
templates = Jinja2Templates(directory="templates")


@app.get("/hello")
async def form_get(request: Request):
    output = "HELLO"
    return templates.TemplateResponse('temp.html', context={'request': request, 'result': output})


@app.get("/dic")
async def form_post(request: Request):
    test = {1: 56, 2: 45, 3: 46, 4: 35, 5: 69}
    return templates.TemplateResponse('temp.html', context={'request': request, 'result': test})

if __name__ == "__main__":
    uvicorn.run("temp:app", reload=True)

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
<p>
    {% if result == "HELLO" %}
        {{ result }}
    {% else %}
        {% for key, value in result.item() %}
            {{ key }} : {{ value }}
        {% endfor %}
    {% endif %}
</p>
</body>
</html>

问题原因

  1. 字典遍历方法错误:Python字典的键值对遍历方法是items(),模板里写成了item()(少了末尾的s),导致Jinja2渲染时找不到该方法,抛出AttributeError,引发500错误。
  2. 判断逻辑局限:原模板只判断result是否等于"HELLO",如果后续新增其他字符串返回的接口,会被错误当成字典处理,导致渲染失败。

修正后的前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
<p>
    {% if isinstance(result, str) %}
        {{ result }}
    {% elif isinstance(result, dict) %}
        {% for key, value in result.items() %}
            {{ key }} : {{ value }}<br>
        {% endfor %}
    {% else %}
        暂不支持的返回类型
    {% endif %}
</p>
</body>
</html>

说明

  • 把result.item()改为result.items(),正确调用字典的遍历方法。
  • 用isinstance(result, str)和isinstance(result, dict)判断返回值类型,覆盖所有字符串和字典的场景,逻辑更健壮。
  • 添加<br>标签让字典的键值对逐行显示,符合需求中的“逐行打印”。

内容的提问来源于stack exchange,提问作者Biswajeet Padhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:50:31