0

I have a fast API server I am building, but the images and CSS files from the template I grabbed are refusing to show up.

Fast API:

from fastapi import FastAPI, status, Response

import asyncio
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.requests import Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

app = FastAPI()

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

templates = Jinja2Templates(directory="templates")

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

The folders are set up as follows:

  • Server.py

  • Templates

    • index.html
    • css
      • template.css
    • img
      • img1
      • img2

There is a templates folder which hosts all of my web files the HTML is in there and inside also are folders for CSS and IMG. I run the code and receive an error that says: ""GET /css/tooplate-vertex.css HTTP/1.1" 404 Not Found". Unsure where this is occurring and I am new to FastAPI, but if this isn't clear let me know.

1
  • what OS are you using? In Linux Templates and templates are different folders. Commented Jun 20, 2022 at 0:55

1 Answer 1

1

Usually you don't keep the static files (i.e. css/images/etc.) in the same directory as your templates (which contain dynamically evaluated HTML). Since you've commented out the StaticFiles handler, there is no way to retrieve these files in your templates - The static handler is responsible for serving any files located under its path directly.

Create a directory named static on the same level as templates (not under it), then enable the static file handler:

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

You can then use the url_for function in your templates to refer to the location of any files under the static file handler dynamically. For example:

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

This will create the URL for the file foo.min.css located under static in your application's directory structure. This leaves you with this common structure instead:

server.py
templates/    
  index.html
static/
  css/
    template.css
  img/
    img1
    img2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.