English 中文(简体)
FastAPI - Static Files
  • 时间:2024-12-22

FastAPI - Static Files


Previous Page Next Page  

Often it is required to include in the template response some resources that remain unchanged even if there is a certain dynamic data. Such resources are called static assets. Media files (.png, .jpg etc), JavaScript files to be used for executing some front end code, or stylesheets for formatting HTML (.CSS files) are the examples of static files.

In order to handle static files, you need a pbrary called aiofiles


pip3 install aiofiles

Next, import StaticFiles class from the fastapi.staticfiles module. Its object is one of the parameters for the mount() method of the FastAPI apppcation object to assign "static" subfolder in the current apppcation folder to store and serve all the static assets of the apppcation.


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

Example

In the following example, FastAPI logo is to be rendered in the hello.html template. Hence, “fa-logo.png” file is first placed in static folder. It is now available for using as src attribute of <img> tag in HTML code.


from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/hello/{name}", response_class=HTMLResponse)
async def hello(request: Request, name:str):
   return templates.TemplateResponse("hello.html", {"request": request, "name":name})

The HTML code of emplateshello.html is as follows −


<html>
   <body>
      <h2>Hello {{name}} Welcome to FastAPI</h2>
      <img src="{{ url_for( static , path= fa-logo.png ) }}" alt="" width="300">
   </body>
</html>
</pre>

Run the Uvicorn server and visit the URL as http://localhost/hello/Vijay. The Logo appears in the browser window as shown.

FastAPI Static Files

Example

Here is another example of a static file. A JavaScript code hello.js contains a definition of myfunction() to be executed on the onload event in following HTML script ( emplateshello.html)


<html>
   <head>
      <title>My Website</title>
      <script src="{{ url_for( static , path= hello.js ) }}"></script>
   </head>
   <body onload="myFunction()">
      <span id="time" style="text-apgn:right; width="100%"></span>
      <h1><span id="ttl">{{ name }}</span></h1>
   </body>
</html>

The hello.js code is as follows − (statichello.js)


function myFunction() {
   var today = new Date();
   var h = today.getHours();
   var m = today.getMinutes();
   var s = today.getSeconds();
   var msg="";
   if (h<12) {
      msg="Good Morning, ";
   }
   if (h>=12 && h<18) {
      msg="Good Afternoon, ";
   }
   if (h>=18) {
      msg="Good Evening, ";
   }
   var x=document.getElementById( ttl ).innerHTML;
   document.getElementById( ttl ).innerHTML = msg+x;
   document.getElementById( time ).innerHTML = h + ":" + m + ":" + s;
}

The function detects the value of current time and assigns appropriate value to msg variable (good morning, good afternoon or good evening) depending on the time of the day.

Save /static/hello.js, modify emplateshello.html and restart the server. The browser should show the current time and corresponding message below it.

FastAPI Static Files FastAPI Static Files Advertisements