在Web应⽤中会出现⼤量的静态⽂件来使得⽹⻚更加⽣动美观。类似于CSS样式⽂件、JavaScript脚本⽂件、图⽚⽂件、字体⽂件等静态资源。那么在FastAPI中怎么让项目能够加载这些静态资源呢?下面我们就来学习一下怎么使用静态资源让您的页面更加美观好看。
安装模块
pip install aiofiles
配置静态资源的路径
下面是main.py文件内容:
from fastapi import FastAPI
from starlette.staticfiles import StaticFiles
app = FastAPI()
# 静态文件配置使用mount挂载 第一个参数为应用的前缀,第二个为路径,第三个为别名
app.mount('/static', StaticFiles(directory='static'), name='static')
注意: /static 这个一定要加上/如果不加的话,会提示下面的错误:
assert path == "" or path.startswith("/"), "Routed paths must start with '/'" AssertionError: Routed paths must start with '/'
另外还需要在main.py同级下创建一个static文件夹。
模板中引入静态资源
假设在我的static文件夹中有demo.css,demo.js,demo.png等静态资源文件。
在模板中引入的方式如下:
<!DOCTYPE html>
<html>
<head>
<title>模板中引入静态资源</title>
<link rel="stylesheet" href="{{ url_for('static',path='demo.css') }}">
</head>
<body>
<div><img src="{{ url_for('static',path='demo.png') }}"></div>
</body>
<script src="{{ url_for('static',path='demo.js') }}"></script>
</html>
注意:{{ url_for('static',path='demo.png') }}中的static是使用app.mount配置时的别名。