1. Jinja

Jinja는 Python에서 사용되는 템플릿 엔진 중 하나로, 템플릿과 데이터를 결합하여 동적인 콘텐츠를 생성하는 데 사용됩니다. 주로 웹 프레임워크에서 HTML 페이지를 동적으로 렌더링하는 데 활용됩니다.

https://jinja.palletsprojects.com/en/3.1.x/

 

2. 설치

Jinja2를 설치합니다.

# Window
pip install jinja2

# macOS
pip3 install jinja2

 

 

3. 간단한 예제

templates라는 디렉토리를 프로젝트 루트에 만들고 그 안에 index.html 파일을 추가합니다.

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ data. title }}</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <h2>안녕! {{ data.name}}</h2>
    <p>{{ request.url }}</p>
</body>
</html>

 

 

main.py 생성 후 작성

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
# Jinja2Templates는 html과 연결시켜주는 역할
# 정적파일을 저장해주는 공간을 생성 StaticFiles -> 가상화시켜서 경로를 만들어줌

# http:// http://127.0.0.1:8000/
app = FastAPI()
templates = Jinja2Templates(directory="templates")

app.mount("/css", StaticFiles(directory="static"), name ="css") # 연결 #/css는 가상의 경로가 됨

@app.get("/")
async def read_root(request: Request):
   # 템플릿에 전달할 데이터
    data = {"name": "뚠빵이", "title": "푸바오 당근뺏기"}
    
    # 템플릿 렌더
    return templates.TemplateResponse("index.html", {"request": request, "data": data})

 

 

http://127.0.0.1:8000/에 액세스하면 FastAPI가 Jinja를 사용하여 동적으로 렌더링한 HTML 페이지를 볼 수 있습니다. 위의 예제에서는 index.html 파일에 정의된 변수 {{ name }}과 {{ title }}에 데이터를 전달하여 동적으로 내용을 생성합니다.

 

uvicorn main:app --reload

 

 

4. 로그인 예제

templates라는 디렉토리를 프로젝트 루트에 만들고 그 안에 login.html 파일과 info.html파일을 추가합니다.

 

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>로그인</title>
</head>
<body>
    <h2>로그인</h2>
    <form action="/login" method="post">
        <p>아이디: <input type="text" name="userid"></p>
        <p>비밀번호: <input type="password" name="userpw"></p>
        <p><button type="submit">로그인</button></p>
    </form>
</body>
</html>

 

info.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>회원정보</title>
</head>
<body>
    <h2>회원정보</h2>
    <p>입력한 아이디는 {{ userid }} 이고, 비밀번호는 {{ userpw }} 입니다!</p>
</body>
</html>

 

 

main.py 파일 생성

 

main.py

from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")

@app.get("/login")
async def login_form(request: Request):
    return templates.TemplateResponse("login.html", {"request": request})

@app.post("/login")
async def login(request: Request, userid: str = Form(...), userpw: str = Form(...)):
    return templates.TemplateResponse("info.html", {"request": request, "userid": userid, "userpw": userpw})
#(...)은 무조건 입력해야 하는것 html의 name = useri와 일치해야함

'컴퓨터 비전 > 웹 서비스' 카테고리의 다른 글

FastAPI  (0) 2023.12.16
Streamlit  (2) 2023.12.03
픽사베이  (1) 2023.12.03
인스타그램  (1) 2023.12.03
셀레니움  (0) 2023.12.02