FastAPI 学习之路(三十八)Static Files

如果使用前后台不分离的开发方式,那么模版文件中使用的静态文件,比如css/js等文件的目录需要在后台进行配置,以便模版渲染是能够正确读取到这些静态文件的。那么我们如何处理呢?

首先安装依赖

pip install aiofiles

我们看下如何使用

        我们定义一个页面,展示一张图片

①:创建两个文件夹static和templates

 

②:分别放置一个home.html和test.png

        其中home.html代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<img src="{{ url_for('static',path='/test.png') }}" style="width: 500px;height: 500px">

</body>
</html>

 ③:我们看下在fastapi中如何使用

from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request


app = FastAPI()

templates = Jinja2Templates(directory="./templates")

app.mount("/static", StaticFiles(directory="./static"), name="static")


@app.get("/")
def home(req: Request):
    return templates.TemplateResponse(
        "home.html",
        {
            "request": req
        }
    )


if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app", reload=True)

通过mount将StaticFiles实例挂载到一个特定的路径上。其中StaticFile类中传递的directory参数是项目中静态文件的目录。

④:启动服务,访问对应接口看效果就可以了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastAPI 是一个现代化的 Web 框架,它基于 Python 3.6+,并使用了一些最新的技术,如 type hints、asyncio 和 Pydantic。FastAPI 可以让你快速地构建高性能的 Web 应用程序和 API。 Swagger 是一种 API 文档和交互式测试工具,它可以帮助开发者快速地了解和测试 APIFastAPI 集成了 Swagger UI,使开发者可以通过浏览器轻松地查看和测试 API。 在 FastAPI 中,只需要使用少量的代码就可以生成 Swagger 文档。你可以使用 FastAPI 内置的 `FastAPIOpenAPI` 和 `FastAPISwaggerUI` 类来集成 Swagger UI,代码示例如下: ```python from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from fastapi.responses import JSONResponse, HTMLResponse from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from fastapi.responses import JSONResponse, HTMLResponse from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from fastapi.responses import JSONResponse, HTMLResponse from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from fastapi.responses import JSONResponse, HTMLResponse app = FastAPI() # 静态文件 app.mount("/static", StaticFiles(directory="static"), name="static") # 模板文件 templates = Jinja2Templates(directory="templates") # 路由 @app.get("/", response_class=HTMLResponse) async def home(request: Request): return templates.TemplateResponse("index.html", {"request": request, "title": "FastAPI"}) @app.get("/docs", response_class=HTMLResponse) async def read_docs(request: Request): return templates.TemplateResponse("docs.html", {"request": request, "title": "API 文档"}) @app.get("/openapi.json", response_class=JSONResponse) async def get_open_api_endpoint(): return JSONResponse(get_openapi(title="FastAPI", version="0.1.0", app=app)) # 启动 FastAPI if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) ``` 在上面的代码中,我们创建了一个 `FastAPI` 实例,并使用 `app.mount` 方法来加载静态文件。然后,我们使用 `Jinja2Templates` 类来加载模板文件。接下来,我们定义了三个路由:`/`、`/docs` 和 `/openapi.json`。其中,`/` 和 `/docs` 路由返回 HTML 页面,`/openapi.json` 路由返回 Swagger 文档。 最后,我们使用 `uvicorn` 模块来启动 FastAPI。启动后,我们可以通过浏览器访问 `http://localhost:8000/docs` 来查看 Swagger UI。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值