- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - Static Files
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.
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.
Advertisements