FastAPI配置系列(二) 靜態文件配置


一、使用方式

如果使用前后台不分離的開發方式,那么模板文件中使用的靜態文件,比如css/js等文件的目錄需要在后台進行配置,以便模板渲染是能正確讀到這些靜態文件。

1、安裝依賴

通過StaticFiles,使用一個目錄自動為靜態文件服務。需要先安裝aiofiles,可以通過:

pip install aiofiles

2、使用StaticFiles

假設現在項目的目錄是這樣的:

│—main.py
│
├─static
│  │  bootstrap.css
│  │  bootstrap.js
│  │
│  └─fonts
│          glyphicons-halflings-regular.eot
│          glyphicons-halflings-regular.svg
│          glyphicons-halflings-regular.ttf
│          glyphicons-halflings-regular.woff
│          glyphicons-halflings-regular.woff2
│
└─templates
        home.html
  • main.py
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()

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

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

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

通過mount將StaticFiles實例掛載到一個特定的路徑上。其中StaticFile類中傳遞的directory參數是項目中靜態文件的目錄。

  • home.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>靜態文件測試</title>
    <link rel="stylesheet" href="{{ url_for('static',path='/bootstrap.css') }}">
    <link rel="stylesheet" href="{{ url_for('static',path='/bootstrap.js') }}">
</head>
<body>
<div class="container">
<form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <div class="form-group">
    <label for="exampleInputFile">File input</label>
    <input type="file" id="exampleInputFile">
    <p class="help-block">Example block-level help text here.</p>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox"> Check me out
    </label>
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>
</html>

在模板文件中引入靜態文件地址。

二、Mounting

"Mounting"意味着添加一個完全獨立的應用在一個特定的路徑上,然后負責處理所有的子路徑。對於StaticFile類中的三個參數:

1、“/static”

所有子應用的子路徑將會掛載到實例上。所以任何以“/static”開頭的路徑資源都可以訪問到。在上面的應用中訪問根目錄,返回home.html頁面,這個頁面中訪問的靜態文件地址:

Request URL: http://127.0.0.1:8000/static/bootstrap.css
...

2、directory="./static"

表示的是應用的靜態文件的實際目錄。

3、name="static"

給一個名稱,用於FastAPI內部調用,所以在home.html中可以使用如下url_for的調用方式引入靜態文件:

<link rel="stylesheet" href="{{ url_for('static',path='/bootstrap.css') }}">

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM