FastAPI返回422错误:HTML中遍历Python列表失败
问题解决步骤
错误原因分析
你遇到的422错误主要由以下几个问题导致:
- FastAPI接口函数错误声明了
dir_files: list参数,框架会将其视为需要从请求中获取的查询参数,但你并未传递该参数 - 模板上下文的键值对写法错误,使用了变量作为键而非字符串
- Jinja2模板的语法错误(循环结束标签格式、变量访问方式)
- 文件路径的转义字符风险
修正后的代码
main.py
from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates import os app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) def print_files(request: Request): # 使用原始字符串避免转义字符问题 proj_dir = r"D:\Project_Dir/" dir_files = os.listdir(proj_dir) dir_files.sort() dir_files = dir_files[:20] # 正确传递模板变量:字符串键对应变量值 return templates.TemplateResponse("file_listing.html", {"request": request, "dir_files": dir_files})
file_listing.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>code_listing</title> </head> <body> <h1>List of files with comments</h1> <!-- 直接使用模板变量,修正循环结束标签格式 --> {% for line in dir_files %} <p>{{ line }}</p> {% endfor %} </body> </html>
关键修正点说明
- 移除不必要的接口参数:删除
dir_files: list参数,因为该变量是在函数内部生成的,不需要从请求中获取 - 修正模板上下文:将
dir_files: list改为"dir_files": dir_files,确保使用字符串作为键,模板才能正确识别变量 - 修复Jinja2语法:
- 直接使用
dir_files变量,无需通过data.get()访问 - 将
{% end-for %}改为标准的{% endfor %}标签格式
- 直接使用
- 优化文件路径:使用原始字符串
r"D:\Project_Dir/"避免转义字符引发的路径解析问题
内容的提问来源于stack exchange,提问作者RTC222
相关产品推荐
相关产品推荐

