Skip to content

๐Ÿ“„

๐Ÿ‘† ๐Ÿ’ช โš™๏ธ ๐Ÿ™† ๐Ÿ“„ ๐Ÿš’ ๐Ÿ‘† ๐Ÿ’š โฎ๏ธ FastAPI.

โš  โš’ Jinja2๏ธโƒฃ, ๐ŸŽ 1๏ธโƒฃ โš™๏ธ ๐Ÿบ & ๐ŸŽ ๐Ÿงฐ.

๐Ÿ“ค ๐Ÿš™ ๐Ÿ”— โšซ๏ธ ๐Ÿ’ช ๐Ÿ‘ˆ ๐Ÿ‘† ๐Ÿ’ช โš™๏ธ ๐Ÿ”— ๐Ÿ‘† FastAPI ๐Ÿˆธ (๐Ÿšš ๐Ÿ’ƒ).

โŽ ๐Ÿ”—

โŽ jinja2:

$ pip install jinja2

---> 100%

โš™๏ธ Jinja2Templates

  • ๐Ÿ—„ Jinja2Templates.
  • โœ templates ๐ŸŽš ๐Ÿ‘ˆ ๐Ÿ‘† ๐Ÿ’ช ๐Ÿค-โš™๏ธ โช.
  • ๐Ÿ“ฃ Request ๐Ÿ”ข โžก ๐Ÿ› ๏ธ ๐Ÿ‘ˆ ๐Ÿ”œ ๐Ÿ“จ ๐Ÿ“„.
  • โš™๏ธ templates ๐Ÿ‘† โœ โœ & ๐Ÿ“จ TemplateResponse, ๐Ÿšถโ€โ™€๏ธ request 1๏ธโƒฃ ๐Ÿ”‘-๐Ÿ’ฒ ๐Ÿ‘ซ Jinja2๏ธโƒฃ "๐Ÿ”‘".
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()

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


templates = Jinja2Templates(directory="templates")


@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
    return templates.TemplateResponse("item.html", {"request": request, "id": id})

Note

๐Ÿ‘€ ๐Ÿ‘ˆ ๐Ÿ‘† โœ”๏ธ ๐Ÿšถโ€โ™€๏ธ request ๐Ÿ• ๐Ÿ”‘-๐Ÿ’ฒ ๐Ÿ‘ซ ๐Ÿ”‘ Jinja2๏ธโƒฃ. , ๐Ÿ‘† โœ”๏ธ ๐Ÿ“ฃ โšซ๏ธ ๐Ÿ‘† โžก ๐Ÿ› ๏ธ.

Tip

๐Ÿ“ฃ response_class=HTMLResponse ๐Ÿฉบ ๐ŸŽš ๐Ÿ”œ ๐Ÿ’ช ๐Ÿ’ญ ๐Ÿ‘ˆ ๐Ÿ“จ ๐Ÿ”œ ๐Ÿ•ธ.

๐Ÿ“ก โ„น

๐Ÿ‘† ๐Ÿ’ช โš™๏ธ from starlette.templating import Jinja2Templates.

FastAPI ๐Ÿšš ๐ŸŽ starlette.templating fastapi.templating ๐Ÿช ๐Ÿ‘†, ๐Ÿ‘ฉโ€๐Ÿ’ป. โœ‹๏ธ ๐ŸŒ… ๐Ÿ’ช ๐Ÿ“จ ๐Ÿ‘Ÿ ๐Ÿ”— โšช๏ธโžก๏ธ ๐Ÿ’ƒ. ๐ŸŽ โฎ๏ธ Request & StaticFiles.

โœ ๐Ÿ“„

โคด๏ธ ๐Ÿ‘† ๐Ÿ’ช โœ ๐Ÿ“„ templates/item.html โฎ๏ธ:

<html>
<head>
    <title>Item Details</title>
    <link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
    <h1>Item ID: {{ id }}</h1>
</body>
</html>

โšซ๏ธ ๐Ÿ”œ ๐ŸŽฆ id โœŠ โšช๏ธโžก๏ธ "๐Ÿ”‘" dict ๐Ÿ‘† ๐Ÿšถโ€โ™€๏ธ:

{"request": request, "id": id}

๐Ÿ“„ & ๐ŸŽป ๐Ÿ“

& ๐Ÿ‘† ๐Ÿ’ช โš™๏ธ url_for() ๐Ÿ”˜ ๐Ÿ“„, & โš™๏ธ โšซ๏ธ, ๐Ÿ–ผ, โฎ๏ธ StaticFiles ๐Ÿ‘† ๐Ÿ“Œ.

<html>
<head>
    <title>Item Details</title>
    <link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
    <h1>Item ID: {{ id }}</h1>
</body>
</html>

๐Ÿ‘‰ ๐Ÿ–ผ, โšซ๏ธ ๐Ÿ”œ ๐Ÿ”— ๐ŸŽš ๐Ÿ“ static/styles.css โฎ๏ธ:

h1 {
    color: green;
}

& โ†ฉ๏ธ ๐Ÿ‘† โš™๏ธ StaticFiles, ๐Ÿ‘ˆ ๐ŸŽš ๐Ÿ“ ๐Ÿ”œ ๐Ÿฆ ๐Ÿ” ๐Ÿ‘† FastAPI ๐Ÿˆธ ๐Ÿ“› /static/styles.css.

๐ŸŒ… โ„น

๐ŸŒ… โ„น, ๐Ÿ”Œ โ” ๐Ÿ’ฏ ๐Ÿ“„, โœ… ๐Ÿ’ƒ ๐Ÿฉบ ๐Ÿ”› ๐Ÿ“„.