环境:
fastapi
app.py
from fastapi import FastAPI, Request, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.concurrency import run_in_threadpool
app = FastAPI(
title="Code Reader",
description="A web application",
version="1.0.0"
)
# 挂载静态文件目录 (CSS, JS)
# 这会创建一个名为 "static" 的路由, 供 Jinja2 的 url_for 使用
app.mount("/static", StaticFiles(directory="static"), name="static")
# 设置 Jinja2 模板目录
templates = Jinja2Templates(directory="templates")
index.html
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>AI代码阅读器 - {{ repo_name }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
……
故障现象
访问http://localhost:5000
页面返回:
{"detail":"Error loading repository: No route exists for name \"static\" and params \"filename\"."}
解决方法:
index.html 修改 url_for中的filename为path
<link rel="stylesheet" href="{{ url_for('static', path='style.css') }}">