Skip to content

Chapter 4

Chapter 4

  • different kinds of response:
  • JSONResponse, HTMLResponse, PlainTextResponse, FileResponse.
  • base class for different response
    from fastapi import Response
    resp = Response(content, media_type)  # e.g. resp = Response("<h1>Hi</h1>", "text/html")
    
  • templates: jinja2
  • fastapi can use jinja2's template mechanism
    from fastapi.templating import Jinja2Templates
    templates = Jinja2Templates(directory="templates")
    
  • Serving static Assets
  • FastAPI facilitates the user of such static files from a location configured for the purpose. These files should be put in a folder named static. It should be in the same folder where the application code script as well as the templates folder resides
  • The path pointing to this static folder is mounted as a subaplication. The mount() method of the Application class defines a /static route mapped to its path
    from fastapi.staticfiles import StaticFiles
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
  • The StaticFiles class (imported from the fastapi.staticfiles module) maps the static directory to the /static route. By mounting a static subapplication, the static content becomes easy to deliver, process, and cache.
  • Whenever we want to use any of these static files, their path is obtained with the url_for() function provided by the jinja2 template language. This can help us avoid referring to the file by its local path and causing a security concern.
  • [???]TODO:
    async def apply(request: Request):
    return templates.TemplateResponse(
        "form.html", {"request": request}
    )
    
  • Not sure what does this request do here.
  • also, don't really know the difference between localhost:8080/form v.s. localhost:8080/form/ (with and without the last /). The first will definitely get routed by app.get("/{name}"), but what is the difference?