fastapi:第二十四章:配置静态文件目录

一,目录结构

image

二,代码

main.py

# main.py
from fastapi import FastAPI
from app.api import products, users, account
from app.core.exceptions import register_exception_handlers
from fastapi.staticfiles import StaticFiles
from app.middleware.api_sign import SignatureMiddleware

# 创建FastAPI应用
app = FastAPI(title="我的API项目")

# 注册全局异常捕获
register_exception_handlers(app)

# 1. 挂载静态文件目录
# path="/static" 是浏览器访问静态文件的 URL 前缀
# directory="app/static" 是本地项目中的文件夹名称
# name="static" 是在 Jinja2 模板中引用时使用的别名
app.mount("/static", StaticFiles(directory="app/static"), name="static")

# 注册路由模块
app.include_router(users.router)
app.include_router(products.router)
app.include_router(account.router)

style.css

body {
    background-color: #f4f4f4;
    font-family: Arial, sans-serif;
}
h1 {
    color: #009688;
}

引用:header.html中引用css样式文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
        <!-- 1. 引用 CSS 静态文件 -->
    <!-- 注意:这里的 'static' 对应后端 app.mount 中的 name="static" -->
    <link rel="stylesheet" href="{{ url_for('static', path='css/style.css') }}">
</head>
<body>
<div style="width:100%;height:50px;background:#eeeeee;">
    <h1 style="text-align:center;">这里是header</h1>
</div>

引用:页面上访问图片

{% include 'block/header.html' %}

<img src="{{ url_for('static', path='images/wine.png') }}" alt="Logo">

{% include 'block/footer.html' %}

三,测试效果 :

image

posted @ 2026-06-12 10:53  刘宏缔的架构森林  阅读(6)  评论(0)    收藏  举报