I read a list of files with os.listdir to display each of the file names in an html page. But when I run this code I get "127.0.0.1:53765 - "GET / HTTP/1.1" 422 Unprocessable Entity."
main.py :
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import os
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
def print_files(request: Request, dir_files: list):
proj_dir = "D:\Project_Dir/"
dir_files = os.listdir(proj_dir)
dir_files.sort()
dir_files = dir_files[:20]
return templates.TemplateResponse("file_listing.html", {"request": request, dir_files: list})
file_listing.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>code_listing</title>
</head>
<body>
<h1>List of files with comments</h1>
{% for line in data.get("dir_files") %}
<p>{{ line }}</p>
{% end-for %}
</body>
</html>
I decided to simplify and pass just a simple list: dir_files = [ "File1", "FIle2", "File3", File4" ]
but I got the same error.
A 422 error means "The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity but was unable to process the contained instructions."
This is my first time looping through a list with FastAPI, so I hope there is a simple solution.