본문 바로가기
Programming/Python_Web

FastAPI - Jinja2로 프론트 적용하기

by Wilkyway 2021. 9. 9.
반응형


1. 설치

pip install fastapi uvicorn 

pip install aiofiles # CSS파일 로딩 

pip install jinja2


2. Project 구성

3. 시작명령어

python app.py


4. app.py

import uvicorn from fastapi 
import FastAPI, Request from fastapi.responses 
import HTMLResponse 
from fastapi.staticfiles import StaticFiles 
from fastapi.templating import Jinja2Templates 

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

@app.get('/') 
def hello_world(): 
	return {'message':'hello'} 

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

if __name__ == '__main__': uvicorn.run(app)


5. /tcmplates/item.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Item Details</title> 
    <link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet"> 
</head> 
<body> 
    <img src="{{ url_for('static', path='/fastapi.png') }}" alt="FastAPI"> 
    <h1>is awesome!</h1> 
    <p>Path for item ID: {{ id }}</p> 
</body> 
</html>


6./static/styles.css

h1{ 
	color: red; text-align: center; 
} 

img { 
  	display: block; 
  	margin-left: auto; 
  	margin-right: auto; 
  	width: 50%; 
}

 

반응형

'Programming > Python_Web' 카테고리의 다른 글

FastAPI - MySQL CRUD  (0) 2021.09.10
FastAPI 시작하기  (0) 2021.09.09
Flask강좌6 - 등록/로그인/로그아웃  (0) 2020.12.04
Flask강좌5 - Flask form입력  (0) 2020.12.03
Flask강좌4 - Flask_SQLAlchemy MySQL연동  (5) 2020.12.02

댓글